gateway: a video reaches a model that takes one, on every API, and a group takes its members' kinds (#6135)

LingYingNX sent MiniMax's Messages video block through the MiniMax plugin
(a plugin is always sent a translated request). readAnthropic had no case
for "video", so the block was left out: the reply was 200, the request
billed, and the model never saw the video. Chat's video_url and a Chat
file of a video were left out the same way (#4101).

A video is now a File part with a video/* media type (video_input.go):
- read from Messages' video block, Chat's video_url, a Chat file of a
  video (nested, or the AI SDK's flat {type, data, mediaType}) and a
  Responses input_file of one;
- built as a video block on Messages, video_url on Chat, inlineData on
  Gemini's API (as before for Gemini);
- Responses has no shape for one: a latest-turn video translated there
  is a 400 that says so (unportableVideo in translate).
A latest-turn video for a model whose list says it takes no video is a
400 before any upstream is asked; one of an earlier turn is told of in
words (Request.videoOff, set in buildFor). A routing group takes the
union of its members' Inputs/Outputs (buildGroupEntries, #2898), so
/v1/models lists video for group/... when a member takes it, and a video
goes only to members that take one, else to unknown ones, else a 400
naming the group.

Not changed: PDFs (Messages document, Responses input_file of a PDF, a
Chat file of a PDF) stay as #5452 says; input_audio stays with #4101.

Ran (mote, at this tree): gofmt -l (nothing), go vet ./...,
GOOS=windows go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=linux go build -tags nogui, GOOS=windows go build,
go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider:
ok gateway (1072s), ok provider (132s).
Rebased on origin/main c4a9856df (3d8510f32 changed Gemini's inlineData,
which passes a video as it is): go vet ./internal/gateway and the video,
group and Gemini media tests again, ok.
New tests: TestPluginGetsTheVideoBlock (the reporter's body shape to a
plugin), TestVideoReachesEveryAPI (Chat video_url / file / AI SDK file /
Responses input_file to Messages, Messages to Chat, Chat to Gemini,
Messages to Responses = 400, Messages relayed), TestVideoForAModelThatTakesNone,
TestGroupVideoGoesToMembersThatTakeIt, TestGroupInputsAreItsMembers.

Broken by hand, each red: the Messages video parse case (4 tests), the
Messages video build, Chat's video build, Chat's video_url parse,
Responses' input_file parse, unportableVideo, the single-model gate, the
group filter, buildFor's videoOff, and unionKinds (provider and gateway
group tests).

Not tried: a real MiniMax account or any real vendor with a video; the
plugin side is plugins#985 (opencode-minimax-auth 0.2.6). The full
suite runs after the push.

Reported-by: LingYingNX
This commit is contained in:
yetone
2026-11-11 19:12:34 +08:00
parent a913464427
commit b4fc29a6e4
11 changed files with 654 additions and 1 deletions
+32
View File
@@ -2308,6 +2308,38 @@ user group and auto group, over Chat, Responses and Messages) and
`TestImageRefused`
([`vision_refused_test.go`](../../internal/gateway/vision_refused_test.go)).
## A video the client gives the model
A video is a `File` part whose media type is `video/*` (`isVideo` in
[`video_input.go`](../../internal/gateway/video_input.go)). It is read from
Messages' `video` block (MiniMax's Anthropic endpoint takes one), Chat's
`video_url`, a Chat `file` of a video (the nested form, or the AI SDK's flat
`{type, data, mediaType}`), a Responses `input_file` of one, and Gemini's
`inlineData`/`fileData`. It is built in each API's own shape: a `video`
block on Messages (`videoBlock`), `video_url` on Chat (`chatVideo`),
`inlineData` on Gemini's API. Responses has none, so a video in the latest
user message translated there is a 400 that says so (`unportableVideo`, in
`translate`). Before, Messages' block and Chat's `video_url` had no case in
the parsers: the request was answered 200 and billed, and the model never
saw the video (#6135, #4101). A relayed body keeps its video as it came.
Whether a model takes video is its source's list of kinds
(`Entry.Inputs`: a plugin's capabilities, a list's `input_modalities`,
models.dev); nil is unknown (`videoInput`). A latest-turn video for a
model known to take none is a 400 before any upstream is asked
(`videoRefused`, in `serve` after the image gate). A video of an earlier
turn to such a model is told of in words (`Request.videoOff`, set in
`buildFor`, `attachmentText`). A routing group takes the union of its
members' kinds (`unionKinds` in `buildGroupEntries`, so `/v1/models` lists
`video` for a group with a member that takes it, #2898), and a video goes
only to the members that take one, else those nothing is known of, else a
400 naming the group. Audio (`input_audio`, #4101) and PDFs (#5452) are not
handled here.
Covered by `TestPluginGetsTheVideoBlock` (the reporter's body to a plugin),
`TestVideoReachesEveryAPI`, `TestVideoForAModelThatTakesNone`,
`TestGroupVideoGoesToMembersThatTakeIt` and `TestGroupInputsAreItsMembers`.
## An image the describer can't describe
`seer` names one describer, and before kelvinjason11 on X ("图片识别好像只支持一个模型识别 没有fallback") that was the only one asked: when it
+16
View File
@@ -205,6 +205,16 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
if b.Source != nil {
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: b.Source.MediaType, Data: b.Source.Data, URL: b.Source.URL, block: true})
}
case "video":
// MiniMax's Anthropic endpoint takes a video in the image
// block's shape (#6135): a File of the video, which every
// builder sends on or turns away, never leaves out
if b.Source != nil {
if v, ok := videoPart(cmp.Or(b.Source.Data, b.Source.URL), cmp.Or(b.Source.MediaType, "video/mp4"), ""); ok {
v.block = true
msg.Parts = append(msg.Parts, v)
}
}
case "tool_use":
msg.Parts = append(msg.Parts, Part{Kind: ToolCall, ID: anthropicInID(b.ID), Name: b.Name, Args: b.Input, block: true})
case "tool_result":
@@ -943,6 +953,12 @@ func anthropicBody(r *Request, model, host string, replay bool) []byte {
rest = append(rest, aBlock{Type: "text", Text: p.Text, CacheControl: partMark(p.cache)})
}
case File:
if isVideo(p) && !r.videoOff {
b := videoBlock(p)
b.CacheControl = partMark(p.cache)
rest = append(rest, b)
break
}
rest = append(rest, aBlock{Type: "text", Text: attachmentText(p)})
case Image:
b := imageBlock(p)
+24
View File
@@ -195,6 +195,14 @@ func chatParts(raw json.RawMessage) []Part {
FileID string `json:"file_id"`
Filename string `json:"filename"`
} `json:"file"`
VideoURL struct {
URL string `json:"url"`
} `json:"video_url"`
// the AI SDK's file part, flat (#4101: ZCode's), whose video
// alone is read here
Data string `json:"data"`
MediaType string `json:"mediaType"`
Filename string `json:"filename"`
}
decodeJSON(raw, &items)
var out []Part
@@ -209,6 +217,17 @@ func chatParts(raw json.RawMessage) []Part {
case "file":
if p, ok := chatFile(it.File.FileData, it.File.FileID, it.File.Filename); ok {
out = append(out, p)
} else if strings.HasPrefix(strings.ToLower(it.MediaType), "video/") {
if v, ok := videoPart(it.Data, it.MediaType, it.Filename); ok {
out = append(out, v)
}
}
case "video_url":
// a video, as DashScope's, Kimi's and OpenRouter's Chat take
// one (#4101, #6135): left out before, and the model answered
// for the words alone
if v, ok := videoPart(it.VideoURL.URL, "", ""); ok {
out = append(out, v)
}
}
}
@@ -490,6 +509,11 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
case Text:
content = append(content, map[string]any{"type": "text", "text": p.Text})
case File:
if isVideo(p) && !r.videoOff {
plain = false
content = append(content, chatVideo(p))
break
}
content = append(content, map[string]any{"type": "text", "text": attachmentText(p)})
case Image:
plain = false
+1 -1
View File
@@ -214,7 +214,7 @@ func renderedCacheBlock(b aBlock) bool {
return b.Thinking != ""
case "redacted_thinking":
return false
case "image":
case "image", "video":
return b.Source != nil && (b.Source.Data != "" || b.Source.URL != "")
}
return true
+45
View File
@@ -2942,6 +2942,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
return
}
}
// a video for a model its list says takes none is turned away, not
// left out for the model to answer the words alone (#6135); a group's
// members are picked by it below
if !isGroup && bytes.Contains(body, []byte("video")) && noVideo(p.ID, model) && hasCurrentVideo(from, body) {
call.Status, call.Error = 400, "model does not support video input"
writeError(w, from, 400, videoRefused(call.Model, ""))
turnedAway()
return
}
// a careful provider's capped accounts read again now where what is
// known of their usage is too old to send on (plugins#349)
if isGroup {
@@ -3285,6 +3294,31 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
}
}
if isGroup && hasCurrentVideo(from, body) {
// a video goes only to the members that take one, else to those
// magpie knows nothing of, else is turned away: a member that takes
// none would answer the words alone (#6135)
var takes, unknown []candidate
var takesAt, unknownAt []Weighed
for i, c := range cands {
switch v := videoInput(c.p.ID, c.model); {
case v == nil:
unknown, unknownAt = append(unknown, c), append(unknownAt, pl.order[i])
case *v:
takes, takesAt = append(takes, c), append(takesAt, pl.order[i])
}
}
cands, pl.order = takes, takesAt
if len(takes) == 0 {
cands, pl.order = unknown, unknownAt
}
if len(cands) == 0 {
call.Status, call.Error = 400, "model does not support video input"
writeError(w, from, 400, videoRefused(call.Model, g.Name))
turnedAway()
return
}
}
pin := strings.TrimSpace(r.Header.Get(AccountHeader))
if pin != "" {
var status int
@@ -8962,6 +8996,10 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
return s.searchReply(w, r, from, p.Name, request, u, ask)
}
}
if msg := unportableVideo(to, request); msg != "" {
// told, not left out for the model to answer the words alone (#6135)
return writeError(w, from, 400, msg), msg
}
stream := request.Stream
request.Stream = true
if stream {
@@ -9329,6 +9367,13 @@ func buildFor(p provider.Provider, proto provider.Protocol, r *Request, model st
c.instructionsKept = true
r = &c
}
if !r.videoOff && anyVideo(r) && noVideo(p.ID, model) {
// a video of an earlier turn, to a model that takes none, is told
// of in words (#6135)
c := *r
c.videoOff = true
r = &c
}
return build(proto, r, model, buildHost(p), p.RejectsTemperature(model))
}
+4
View File
@@ -247,6 +247,10 @@ type Request struct {
// client asked prompt_cache_retention "in_memory", or the upstream
// turned the ttl away (hourMarksRefused).
hourMarks bool
// videoOff is set on a request built for a model known not to take
// video (videoInput): a video of an earlier turn is told of in words
// (attachmentText) where it would go as a video block (video_input.go)
videoOff bool
// draws asks the model for images beside text: a drawing asked on
// Gemini's API of a model not named for images (drawCodeAssist).
draws bool
+11
View File
@@ -1105,6 +1105,9 @@ func responsesParts(raw json.RawMessage) []Part {
Text string `json:"text"`
ImageURL string `json:"image_url"`
Detail string `json:"detail"`
FileData string `json:"file_data"`
FileURL string `json:"file_url"`
Filename string `json:"filename"`
}
decodeJSON(raw, &items)
var out []Part
@@ -1118,6 +1121,14 @@ func responsesParts(raw json.RawMessage) []Part {
im.Detail = it.Detail
out = append(out, im)
}
case "input_file":
// a video alone (#6135); another file is still left out (#5452)
src := cmp.Or(it.FileData, it.FileURL)
if mt := videoFileType(src, it.Filename); mt != "" {
if v, ok := videoPart(src, mt, it.Filename); ok {
out = append(out, v)
}
}
}
}
return out
+169
View File
@@ -0,0 +1,169 @@
package gateway
import (
"bytes"
"cmp"
"fmt"
"mime"
"path"
"slices"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// A video a client gives the model (#6135, #4101) is a File part whose
// media type is video/*: Messages' video block (MiniMax's Anthropic
// endpoint takes one), Chat's video_url, a Chat file or Responses
// input_file of a video, and Gemini's inlineData or fileData of one. It
// goes to the upstream in that API's own shape: a video block on
// Messages, video_url on Chat, inlineData on Gemini's API. Responses has
// none, so a video in the latest turn translated there is turned away
// (unportableVideo), as is one for a model whose source says it takes no
// video (videoInput) or a group with no member that takes one. A video of
// an earlier turn to such a model is told of in words (attachmentText), as
// an image of an earlier turn is to a text-only model.
//
// Before, Messages' video block and Chat's video_url had no case in the
// parsers and were left out: the vendor answered 200 for the words alone
// and the model said it saw no video, or made one up.
// isVideo is whether p is a video the client gave.
func isVideo(p Part) bool {
return p.Kind == File && strings.HasPrefix(strings.ToLower(p.MediaType), "video/")
}
// videoPart is a video by its data: URL, bare base64 or address, with the
// media type the client named, else the one its data: URL or its name's
// extension says, else video/mp4; false for one with nothing in it.
func videoPart(src, mediaType, name string) (Part, bool) {
if src == "" {
return Part{}, false
}
if strings.HasPrefix(src, "data:") {
p := imagePart(src)
if p.Data == "" {
return Part{}, false
}
return Part{Kind: File, MediaType: cmp.Or(mediaType, p.MediaType, videoByName(name), "video/mp4"), Data: p.Data}, true
}
if strings.Contains(src, "://") {
at, _, _ := strings.Cut(src, "?")
return Part{Kind: File, MediaType: cmp.Or(mediaType, videoByName(cmp.Or(name, at)), "video/mp4"), URL: src}, true
}
return Part{Kind: File, MediaType: cmp.Or(mediaType, videoByName(name), "video/mp4"), Data: src}, true
}
// videoByName is the video media type a file's name says, "" for none.
func videoByName(name string) string {
mt, _, _ := strings.Cut(mime.TypeByExtension(strings.ToLower(path.Ext(name))), ";")
if strings.HasPrefix(mt, "video/") {
return mt
}
return ""
}
// videoInput is whether the model p serves as model takes video, from the
// kinds its source listed (Entry.Inputs: a plugin's capabilities, a model
// list's input_modalities, models.dev); nil when it listed none.
func videoInput(id, model string) *bool {
for _, e := range provider.Served() {
if e.Group == "" && e.Provider.ID == id && e.Model == model {
if e.Inputs == nil {
return nil
}
takes := slices.Contains(e.Inputs, "video")
return &takes
}
}
return nil
}
// noVideo is whether the model is known to take no video.
func noVideo(id, model string) bool {
v := videoInput(id, model)
return v != nil && !*v
}
// currentVideo is whether the request's latest user message gives the
// model a video, the one it is asked about now.
func currentVideo(r *Request) bool {
for i := len(r.Messages) - 1; i >= 0; i-- {
if m := r.Messages[i]; m.Role == "user" {
return slices.ContainsFunc(m.Parts, isVideo)
}
}
return false
}
// hasCurrentVideo is currentVideo of a body as the client sent it. Most
// bodies name no video at all and are not parsed.
func hasCurrentVideo(from provider.Protocol, body []byte) bool {
if !bytes.Contains(body, []byte("video")) {
return false
}
req, err := parse(from, body)
return err == nil && currentVideo(req)
}
// videoRefused is what the agent is told of a video for a model, or a
// group, that takes none.
func videoRefused(model, group string) string {
if group != "" {
return fmt.Sprintf("model %q does not support video input: no model of the routing group %s takes video. Add a member that takes video, or send frames as images", model, group)
}
return fmt.Sprintf("model %q does not support video input: its model list doesn't say it takes video. Send frames as images, or pick a model that takes video", model)
}
// unportableVideo is the 400 for a video in the latest turn translated to
// an API that has no way to carry one; "" when it can be carried.
func unportableVideo(to provider.Protocol, r *Request) string {
if to != provider.Responses || !currentVideo(r) {
return ""
}
return "this request gives the model a video, which the Responses API has no way to carry; send it on Chat, Messages or Gemini's API, or send frames as images"
}
// chatVideo is a video as Chat's video_url part, the shape the Chat APIs
// that take video read (DashScope's Qwen, Kimi, Zhipu, OpenRouter, vLLM).
func chatVideo(p Part) map[string]any {
return map[string]any{"type": "video_url", "video_url": map[string]any{"url": dataURL(p)}}
}
// videoBlock is a video as a Messages video block, the image block's shape
// under another type: MiniMax's Anthropic endpoint reads it.
func videoBlock(p Part) aBlock {
b := imageBlock(p)
b.Type = "video"
return b
}
// videoFileType is the video media type of a Responses input_file, by its
// data: URL's type or its name; "" for a file that is not a video.
func videoFileType(src, name string) string {
if rest, ok := strings.CutPrefix(src, "data:"); ok {
mt, _, _ := strings.Cut(rest, ";")
mt, _, _ = strings.Cut(mt, ",")
if strings.HasPrefix(strings.ToLower(mt), "video/") {
return strings.ToLower(mt)
}
if mt != "" {
return ""
}
}
at, _, _ := strings.Cut(src, "?")
if strings.Contains(src, "://") {
return cmp.Or(videoByName(name), videoByName(at))
}
return videoByName(name)
}
// anyVideo is whether any message of the request gives a video.
func anyVideo(r *Request) bool {
for _, m := range r.Messages {
if slices.ContainsFunc(m.Parts, isVideo) {
return true
}
}
return false
}
+295
View File
@@ -0,0 +1,295 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// the start of an MP4 (its ftyp box), as base64
const videoData = "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDE="
// The reporter's request (#6135): MiniMax's Messages video block beside
// the words, sent to the MiniMax plugin as one JSON body.
const reporterVideoBody = `{"model":"m1","max_tokens":256,"messages":[{"role":"user","content":[{"type":"video","source":{"type":"base64","media_type":"video/mp4","data":"` + videoData + `"}},{"type":"text","text":"用一句话描述这段视频画面。"}]}]}`
// A Messages video block reaches a plugin, which is always sent a
// translated request (Account.Stream): before, the block had no case in
// the parser and was left out, so MiniMax answered 200 for the words
// alone and the model said it saw no video (#6135).
func TestPluginGetsTheVideoBlock(t *testing.T) {
f, up := pluginFake(t)
code, msg, _, asked := pluginTranslate(t, f, up, reporterVideoBody)
if code != 200 {
t.Fatalf("%d: %s", code, msg)
}
var wire struct {
Messages []struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
Source *struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data string `json:"data"`
} `json:"source"`
} `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(asked, &wire); err != nil || len(wire.Messages) != 1 {
t.Fatalf("asked %s (%v)", asked, err)
}
c := wire.Messages[0].Content
if len(c) != 2 || c[0].Type != "video" || c[0].Source == nil || c[0].Source.Type != "base64" ||
c[0].Source.MediaType != "video/mp4" || c[0].Source.Data != videoData ||
c[1].Type != "text" || c[1].Text != "用一句话描述这段视频画面。" {
t.Fatalf("the video didn't reach the plugin as the client gave it: %s", asked)
}
}
type videoUpstream struct {
mu sync.Mutex
bodies []string
models []string
}
func (v *videoUpstream) sent() ([]string, []string) {
v.mu.Lock()
defer v.mu.Unlock()
return slices.Clone(v.bodies), slices.Clone(v.models)
}
func (v *videoUpstream) reset() {
v.mu.Lock()
v.bodies, v.models = nil, nil
v.mu.Unlock()
}
// videoUp is an upstream that answers each API in its own shape.
func videoUp(t *testing.T) (*videoUpstream, *httptest.Server) {
v := &videoUpstream{}
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var req struct{ Model string }
json.Unmarshal(b, &req)
v.mu.Lock()
v.bodies, v.models = append(v.bodies, string(b)), append(v.models, req.Model)
v.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
switch {
case strings.Contains(strings.ToLower(r.URL.Path), "generatecontent"):
io.WriteString(w, "data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}],\"usageMetadata\":{\"promptTokenCount\":1,\"candidatesTokenCount\":1}}\n\n")
case strings.Contains(r.URL.Path, "messages"):
io.WriteString(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"v\",\"content\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n"+
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"+
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\n"+
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"+
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n"+
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")
default:
io.WriteString(w, "data: {\"id\":\"x\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"}}]}\n\n"+
"data: {\"id\":\"x\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1}}\n\ndata: [DONE]\n\n")
}
}))
t.Cleanup(up.Close)
return v, up
}
var videoKinds = []string{"text", "image", "video"}
func saveVideoProvider(t *testing.T, p provider.Provider, url string) {
t.Helper()
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive(p.ID, url, []catalog.Model{
{ID: "v", Images: true, ImageInput: imageInputBool(true), InputModalities: videoKinds, OutputModalities: []string{"text"}},
{ID: "t", Images: true, ImageInput: imageInputBool(true), InputModalities: []string{"text", "image"}, OutputModalities: []string{"text"}},
{ID: "u"},
}); err != nil {
t.Fatal(err)
}
}
func serveVideo(s *Server, path, body string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
return rec
}
// A video reaches the upstream on every API that carries content blocks,
// in that API's own shape: Chat's video_url, a Chat file of a video and a
// Responses input_file of one go to a Messages upstream as a video block,
// and a Messages video block goes to a Chat upstream as video_url
// (#6135, #4101). Where it can't be carried, the client is told.
func TestVideoReachesEveryAPI(t *testing.T) {
fresh(t)
noVision(t)
anth, anthUp := videoUp(t)
saveVideoProvider(t, provider.Provider{ID: "anth", Name: "Anth", Anthropic: anthUp.URL, Key: "k", Models: []string{"v", "t", "u"}}, anthUp.URL)
chat, chatUp := videoUp(t)
saveVideoProvider(t, provider.Provider{ID: "chat", Name: "Chat", Chat: chatUp.URL + "/v1", Key: "k", Models: []string{"v", "t", "u"}}, chatUp.URL+"/v1")
resp, respUp := videoUp(t)
saveVideoProvider(t, provider.Provider{ID: "resp", Name: "Resp", Responses: respUp.URL + "/v1", Key: "k", Models: []string{"v", "t", "u"}}, respUp.URL+"/v1")
s := New()
url := "data:video/mp4;base64," + videoData
for name, body := range map[string]string{
"chat video_url": `{"model":"anth/v","messages":[{"role":"user","content":[{"type":"video_url","video_url":{"url":"` + url + `"}},{"type":"text","text":"用一句话描述这段视频画面。"}]}]}`,
"chat file": `{"model":"anth/v","messages":[{"role":"user","content":[{"type":"file","file":{"file_data":"` + url + `","filename":"clip.mp4"}},{"type":"text","text":"用一句话描述这段视频画面。"}]}]}`,
"chat AI SDK file": `{"model":"anth/v","messages":[{"role":"user","content":[{"type":"file","data":"` + videoData + `","mediaType":"video/mp4","filename":"clip.mp4"},{"type":"text","text":"用一句话描述这段视频画面。"}]}]}`,
// #4101's own shape: the AI SDK's file with a data: URL
"chat AI SDK file, data URL": `{"model":"anth/v","messages":[{"role":"user","content":[{"type":"text","text":"用一句话描述这段视频的画面内容。"},{"type":"file","mediaType":"video/mp4","data":"` + url + `"}]}]}`,
} {
anth.reset()
rec := serveVideo(s, "/v1/chat/completions", body)
bodies, _ := anth.sent()
if rec.Code != 200 || len(bodies) != 1 || !strings.Contains(bodies[0], `{"type":"video","source":{"type":"base64","media_type":"video/mp4","data":"`+videoData+`"}`) {
t.Errorf("%s to Messages: %d %s; upstream %v", name, rec.Code, rec.Body.String(), bodies)
}
}
anth.reset()
rec := serveVideo(s, "/v1/responses", `{"model":"anth/v","input":[{"role":"user","content":[{"type":"input_file","file_data":"`+url+`","filename":"clip.mp4"},{"type":"input_text","text":"用一句话描述这段视频画面。"}]}]}`)
if bodies, _ := anth.sent(); rec.Code != 200 || len(bodies) != 1 || !strings.Contains(bodies[0], `"type":"video"`) || !strings.Contains(bodies[0], videoData) {
t.Errorf("Responses input_file to Messages: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
messages := strings.Replace(reporterVideoBody, `"m1"`, `"chat/v"`, 1)
rec = serveVideo(s, "/v1/messages", messages)
if bodies, _ := chat.sent(); rec.Code != 200 || len(bodies) != 1 || !strings.Contains(bodies[0], `{"type":"video_url","video_url":{"url":"`+url+`"}}`) {
t.Errorf("Messages video to Chat: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
// #4101's: Chat's video_url to Gemini's API, as inlineData
gem, gemUp := videoUp(t)
saveVideoProvider(t, provider.Provider{ID: "gem", Name: "Gem", Gemini: gemUp.URL + "/v1beta", Key: "k", Models: []string{"v", "t", "u"}}, gemUp.URL+"/v1beta")
rec = serveVideo(s, "/v1/chat/completions", `{"model":"gem/v","messages":[{"role":"user","content":[{"type":"text","text":"用一句话描述这段视频的画面内容。"},{"type":"video_url","video_url":{"url":"`+url+`"}}]}]}`)
if bodies, _ := gem.sent(); rec.Code != 200 || len(bodies) != 1 || !strings.Contains(bodies[0], `"mimeType":"video/mp4"`) || !strings.Contains(bodies[0], videoData) {
t.Errorf("Chat video_url to Gemini: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
// Responses has no way to carry one
rec = serveVideo(s, "/v1/messages", strings.Replace(reporterVideoBody, `"m1"`, `"resp/v"`, 1))
if bodies, _ := resp.sent(); rec.Code != 400 || !strings.Contains(rec.Body.String(), "Responses API has no way to carry") || len(bodies) != 0 {
t.Errorf("Messages video to Responses: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
// relayed as it came, on the client's own API
anth.reset()
rec = serveVideo(s, "/v1/messages", strings.Replace(reporterVideoBody, `"m1"`, `"anth/v"`, 1))
if bodies, _ := anth.sent(); rec.Code != 200 || len(bodies) != 1 || !strings.Contains(bodies[0], `"type":"video"`) || !strings.Contains(bodies[0], videoData) {
t.Errorf("Messages video to Messages: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
}
// A video for a model whose list says it takes none is turned away with
// why, not sent to answer the words alone; a model its list says nothing
// of is sent it, and a video of an earlier turn is told of in words to a
// model that takes none (#6135).
func TestVideoForAModelThatTakesNone(t *testing.T) {
fresh(t)
noVision(t)
anth, anthUp := videoUp(t)
saveVideoProvider(t, provider.Provider{ID: "anth", Name: "Anth", Anthropic: anthUp.URL, Key: "k", Models: []string{"v", "t", "u"}}, anthUp.URL)
chat, chatUp := videoUp(t)
saveVideoProvider(t, provider.Provider{ID: "chat", Name: "Chat", Chat: chatUp.URL + "/v1", Key: "k", Models: []string{"v", "t", "u"}}, chatUp.URL+"/v1")
s := New()
for _, path := range []string{"/v1/messages", "/v1/chat/completions"} {
body := strings.Replace(reporterVideoBody, `"m1"`, `"anth/t"`, 1)
if path == "/v1/chat/completions" {
body = `{"model":"anth/t","messages":[{"role":"user","content":[{"type":"video_url","video_url":{"url":"data:video/mp4;base64,` + videoData + `"}},{"type":"text","text":"用一句话描述这段视频画面。"}]}]}`
}
rec := serveVideo(s, path, body)
if rec.Code != 400 || !strings.Contains(rec.Body.String(), "does not support video input") {
t.Errorf("%s video to a model that takes none: %d %s", path, rec.Code, rec.Body.String())
}
}
if bodies, _ := anth.sent(); len(bodies) != 0 {
t.Fatalf("a video for a model that takes none reached upstream: %v", bodies)
}
rec := serveVideo(s, "/v1/messages", strings.Replace(reporterVideoBody, `"m1"`, `"anth/u"`, 1))
if bodies, _ := anth.sent(); rec.Code != 200 || len(bodies) != 1 || !strings.Contains(bodies[0], videoData) {
t.Errorf("video to a model nothing is known of: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
earlier := `{"model":"chat/t","max_tokens":256,"messages":[` +
`{"role":"user","content":[{"type":"video","source":{"type":"base64","media_type":"video/mp4","data":"` + videoData + `"}},{"type":"text","text":"用一句话描述这段视频画面。"}]},` +
`{"role":"assistant","content":[{"type":"text","text":"一只猫。"}]},` +
`{"role":"user","content":[{"type":"text","text":"谢谢"}]}]}`
rec = serveVideo(s, "/v1/messages", earlier)
bodies, _ := chat.sent()
if rec.Code != 200 || len(bodies) != 1 || strings.Contains(bodies[0], videoData) || strings.Contains(bodies[0], "video_url") ||
!strings.Contains(bodies[0], "[attachment video/mp4]") {
t.Errorf("an earlier video to a model that takes none: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
}
// A routing group says it takes video when a member does, and gives a
// video only to the members that take one (#2898, #6135).
func TestGroupVideoGoesToMembersThatTakeIt(t *testing.T) {
fresh(t)
noVision(t)
anth, anthUp := videoUp(t)
saveVideoProvider(t, provider.Provider{ID: "anth", Name: "Anth", Anthropic: anthUp.URL, Key: "k", Models: []string{"v", "t", "u"}}, anthUp.URL)
if err := provider.SaveGroup(provider.Group{Name: "Mixed", Members: []string{"anth/t", "anth/v"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{Name: "Blind", Members: []string{"anth/t"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
var list struct {
Data []struct {
ID string `json:"id"`
Modalities *struct {
Input []string `json:"input"`
} `json:"modalities"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil {
t.Fatal(err)
}
inputs := map[string][]string{}
for _, m := range list.Data {
if m.Modalities != nil {
inputs[m.ID] = m.Modalities.Input
}
}
if !slices.Contains(inputs["group/mixed"], "video") {
t.Errorf("group/mixed takes %v, want video among them", inputs["group/mixed"])
}
if in := inputs["group/blind"]; slices.Contains(in, "video") || !slices.Contains(in, "image") {
t.Errorf("group/blind takes %v, want image and no video", in)
}
rec = serveVideo(s, "/v1/messages", strings.Replace(reporterVideoBody, `"m1"`, `"group/mixed"`, 1))
bodies, models := anth.sent()
if rec.Code != 200 || len(bodies) != 1 || models[0] != "v" || !strings.Contains(bodies[0], videoData) {
t.Errorf("group video: %d %s; upstream %v to %v", rec.Code, rec.Body.String(), bodies, models)
}
// a request with no video keeps the members' order
anth.reset()
rec = serveVideo(s, "/v1/messages", `{"model":"group/mixed","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`)
if _, models := anth.sent(); rec.Code != 200 || len(models) != 1 || models[0] != "t" {
t.Errorf("group words: %d %s; upstream to %v", rec.Code, rec.Body.String(), models)
}
anth.reset()
rec = serveVideo(s, "/v1/messages", strings.Replace(reporterVideoBody, `"m1"`, `"group/blind"`, 1))
if bodies, _ := anth.sent(); rec.Code != 400 || !strings.Contains(rec.Body.String(), "does not support video input") || len(bodies) != 0 {
t.Errorf("group with no member that takes video: %d %s; upstream %v", rec.Code, rec.Body.String(), bodies)
}
}
+32
View File
@@ -1480,10 +1480,14 @@ func buildGroupEntries(entries []Entry) []Entry {
var efforts []string
images, thinks, ctx, output := false, false, 0, 0
var imageInput *bool
// the kinds of input and output the member's source listed
// (video, audio and pdf beside image, #1595)
var inputs, outputs []string
unknown, reasonless, typed := false, false, false
if j := find(m.Provider.ID, m.Model); j >= 0 {
x := &entries[j]
efforts, images, thinks, ctx, output, imageInput = x.Efforts, x.Images, x.Reasoning, x.Context, x.Output, x.ImageInput
inputs, outputs = x.Inputs, x.Outputs
typed = x.WindowSet
unknown, reasonless = levelsUnknown(*x), x.Reasonless
}
@@ -1510,6 +1514,14 @@ func buildGroupEntries(entries []Entry) []Entry {
// group of DeepSeek V4.1 Flash with a text-only member in it
// turned every image away, though its other members see)
e.Images = e.Images || images
// and every other kind a member takes or gives, a video among
// them: the gateway sends a request with a video only to the
// members that take one (videoInput in the gateway), as it does
// an image. Left nil, Modalities fell back to text and image,
// and a group of MiniMax M3.1 Flash, which takes video, was
// listed as not taking it (#2898, #6135)
e.Inputs = unionKinds(e.Inputs, inputs)
e.Outputs = unionKinds(e.Outputs, outputs)
// the window agents are told is the largest a member has:
// a conversation too long for one member goes on to a member
// with room for it (#700, withRoom in the gateway), so the
@@ -1631,6 +1643,26 @@ func buildGroupEntries(entries []Entry) []Entry {
return out
}
// unionKinds is every kind a or b lists, in the order given; nil when
// neither lists any, which is not an empty list: Modalities falls back to
// text and image on nil (an entry whose source said nothing), and reads a
// list as it is.
func unionKinds(a, b []string) []string {
if a == nil && b == nil {
return nil
}
out := slices.Clone(a)
if out == nil {
out = []string{}
}
for _, k := range b {
if !slices.Contains(out, k) {
out = append(out, k)
}
}
return out
}
// smallestWindow is the smallest window a member of ms is known to have
// (0 when none is), and whether the user typed it, on the member's
// provider for its model or all of its models. A group told its
+25
View File
@@ -2,6 +2,7 @@ package provider
import (
"maps"
"slices"
"testing"
)
@@ -80,6 +81,30 @@ func TestGroupImagesFromAMemberThatSees(t *testing.T) {
}
}
// A group takes every kind a member takes, not text and image alone
// (#2898, #6135), and says nothing of the kinds when no member did.
func TestGroupInputsAreItsMembers(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", "")
entries := []Entry{
{ID: "a/m", Model: "m", Provider: Provider{ID: "a"}, Images: true, Inputs: []string{"text", "image"}, Outputs: []string{"text"}},
{ID: "b/m", Model: "m", Provider: Provider{ID: "b"}, Images: true, Inputs: []string{"text", "image", "video"}, Outputs: []string{"text"}},
{ID: "a/n", Model: "n", Provider: Provider{ID: "a"}},
{ID: "b/n", Model: "n", Provider: Provider{ID: "b"}},
}
got := map[string]Entry{}
for _, g := range groupEntries(entries) {
got[g.Model] = g
}
if g := got["m"]; !slices.Equal(g.Inputs, []string{"text", "image", "video"}) || !slices.Equal(g.Outputs, []string{"text"}) {
t.Errorf("group of m takes %v, gives %v", g.Inputs, g.Outputs)
}
if g, ok := got["n"]; !ok || g.Inputs != nil || g.Outputs != nil {
t.Errorf("group of n, no member said of: %+v (%v)", g, ok)
}
}
// A group whose first member is a ChatGPT account's model is still magpie's
// to list to a signed-in Codex: the backend lists the model, not the group.
func TestCodexListedKeepsGroups(t *testing.T) {