gateway: Gemini PDF and audio files kept on text-only routes (#95)

* gateway: keep Gemini document and audio file data on text-only routes

* fix(gateway): avoid translating Gemini files as images

* fix(gateway): preserve Gemini files for Code Assist while translating safely

* fix(gateway): retain Gemini file placeholder for Claude subscriptions

---------

Co-authored-by: Instinct Agent <agent@instinct.com>
Co-authored-by: Charan Rathore <charan-rathore@users.noreply.github.com>
This commit is contained in:
Charan Rathore
2026-09-27 04:24:03 +08:00
committed by GitHub
co-authored by Instinct Agent Charan Rathore
parent a90e9ae4e5
commit e136cf9a27
11 changed files with 120 additions and 6 deletions
+1 -1
View File
@@ -88,7 +88,7 @@ func turnIn(req *Request) (turn int, within bool) {
text, result := false, false
for _, p := range m.Parts {
switch p.Kind {
case Text, Image:
case Text, Image, File:
text = true
case ToolResult:
result = true
+2
View File
@@ -224,6 +224,8 @@ func buildAnthropic(r *Request, model string) []byte {
if strings.TrimSpace(p.Text) != "" {
rest = append(rest, aBlock{Type: "text", Text: p.Text})
}
case File:
rest = append(rest, aBlock{Type: "text", Text: attachmentText(p)})
case Image:
b := aBlock{Type: "image"}
b.Source = &struct {
+2
View File
@@ -222,6 +222,8 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
switch p.Kind {
case Text:
content = append(content, map[string]any{"type": "text", "text": p.Text})
case File:
content = append(content, map[string]any{"type": "text", "text": attachmentText(p)})
case Image:
plain = false
content = append(content, map[string]any{"type": "image_url", "image_url": map[string]any{"url": dataURL(p)}})
+4
View File
@@ -351,6 +351,8 @@ func turnKey(owner string, req *Request, msgs []Message) string {
fmt.Fprintf(&b, "\x01call %s %s ", p.Name, p.ID)
case ToolResult:
fmt.Fprintf(&b, "\x01result %s %s ", p.CallID, p.Text)
case File:
fmt.Fprintf(&b, "\x01file %s %d %s ", p.MediaType, len(p.Data), p.URL)
case Image:
fmt.Fprintf(&b, "\x01image %d %s ", len(p.Data), p.URL)
}
@@ -663,6 +665,8 @@ func renderParts(blocks []map[string]any, text *strings.Builder, parts []Part) [
switch p.Kind {
case Text:
text.WriteString(p.Text)
case File:
text.WriteString(attachmentText(p))
case Thinking:
text.WriteString(p.Text)
case ToolCall:
+1 -1
View File
@@ -46,7 +46,7 @@ func buildCodeAssist(r *Request, model, agent string) []byte {
if p.Text != "" {
parts = append(parts, map[string]any{"text": p.Text})
}
case Image:
case Image, File:
if p.Data != "" {
parts = append(parts, map[string]any{"inlineData": map[string]any{"mimeType": p.MediaType, "data": p.Data}})
} else if p.URL != "" {
+7 -2
View File
@@ -145,10 +145,15 @@ func parseGemini(body []byte) (*Request, error) {
if strings.HasPrefix(p.InlineData.MimeType, "image/") {
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: p.InlineData.MimeType, Data: p.InlineData.Data})
} else {
msg.Parts = append(msg.Parts, Part{Kind: Text, Text: "[attachment " + p.InlineData.MimeType + "]"})
msg.Parts = append(msg.Parts, Part{Kind: File, MediaType: p.InlineData.MimeType, Data: p.InlineData.Data})
}
case p.FileData != nil:
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: p.FileData.MimeType, URL: p.FileData.FileURI})
if strings.HasPrefix(p.FileData.MimeType, "image/") {
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: p.FileData.MimeType, URL: p.FileData.FileURI})
} else {
// Other protocols cannot carry Gemini file references as image URLs.
msg.Parts = append(msg.Parts, Part{Kind: File, MediaType: p.FileData.MimeType, URL: p.FileData.FileURI})
}
case p.Thought:
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: p.Text, Signature: p.Signature})
case p.Text != "":
+9 -1
View File
@@ -92,7 +92,15 @@ func omitImageBlocks(proto provider.Protocol, raw json.RawMessage) (json.RawMess
MimeType string `json:"mimeType"`
}
json.Unmarshal(block["inlineData"], &data)
isImage = strings.HasPrefix(data.MimeType, "image/") || len(block["fileData"]) > 0
isImage = strings.HasPrefix(data.MimeType, "image/")
if len(block["fileData"]) > 0 {
var file struct {
MimeType string `json:"mimeType"`
}
if json.Unmarshal(block["fileData"], &file) != nil || file.MimeType == "" || strings.HasPrefix(file.MimeType, "image/") {
isImage = true // unknown file types may be images; fail closed
}
}
}
if isImage {
blocks[i] = imagePlaceholder(proto)
+75
View File
@@ -390,3 +390,78 @@ func TestFailedKeyFetchKeepsUnknownImageCapabilityAtGateway(t *testing.T) {
t.Fatalf("image after failed key fetch: %d %s; upstream got %d images", rec.Code, rec.Body.String(), sent)
}
}
// Gemini fileData also carries documents and audio. A text-only model must
// reject images, but it must not silently discard a non-image file part.
func TestGeminiTextOnlyBodyKeepsNonImageFileData(t *testing.T) {
for _, tc := range []struct {
mime string
blocked bool
}{
{"application/pdf", false},
{"audio/wav", false},
{"image/png", true},
} {
source := `{"contents":[{"role":"user","parts":[{"text":"read this"},{"fileData":{"mimeType":"` + tc.mime + `","fileUri":"gs://bucket/file"}}]}]}`
body, blocked := textOnlyBody(provider.Gemini, []byte(source))
if blocked != tc.blocked {
t.Errorf("%s blocked=%v, want %v", tc.mime, blocked, tc.blocked)
}
if !tc.blocked && !strings.Contains(string(body), "gs://bucket/file") {
t.Errorf("%s was stripped: %s", tc.mime, body)
}
}
}
// A non-image Gemini file must not become image_url when routed to Chat.
func TestGeminiNonImageFileTranslation(t *testing.T) {
for _, tc := range []struct {
name, mime, field, value string
}{
{"file-pdf", "application/pdf", "fileData", `"fileUri":"gs://bucket/file.pdf"`},
{"file-audio", "audio/wav", "fileData", `"fileUri":"gs://bucket/file.wav"`},
{"inline-pdf", "application/pdf", "inlineData", `"data":"cGRm"`},
} {
t.Run(tc.name, func(t *testing.T) {
source := `{"contents":[{"role":"user","parts":[{"text":"read this"},{"` + tc.field + `":{"mimeType":"` + tc.mime + `",` + tc.value + `}}]}]}`
body, blocked := textOnlyBody(provider.Gemini, []byte(source))
if blocked {
t.Fatal("non-image attachment blocked as image")
}
r, err := parseGemini(body)
if err != nil {
t.Fatal(err)
}
claude, err := renderClaudePrompt(r)
if err != nil {
t.Fatal(err)
}
prompt, err := json.Marshal(claude)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(prompt), "[attachment "+tc.mime) || strings.Contains(string(prompt), `"type":"image"`) {
t.Fatalf("Claude subscription lost or mislabeled file: %s", prompt)
}
chat := buildChat(r, "text", "", false)
if strings.Contains(string(chat), `"image_url"`) || !strings.Contains(string(chat), "[attachment "+tc.mime) {
t.Fatalf("non-image attachment translated as an image or lost: %s", chat)
}
// Code Assist speaks Gemini's file format and must keep the data.
assist := buildCodeAssist(r, "gemini-2.5-pro", "gemini")
if !strings.Contains(string(assist), `"`+tc.field+`"`) || !strings.Contains(string(assist), tc.value) {
t.Fatalf("Gemini attachment lost in Code Assist: %s", assist)
}
if strings.Contains(string(assist), "[attachment ") {
t.Fatalf("Code Assist received a placeholder instead of the file: %s", assist)
}
responses := buildResponses(r, "text", "", false)
anthropic := buildAnthropic(r, "text")
for protocol, out := range map[string][]byte{"Responses": responses, "Anthropic": anthropic} {
if strings.Contains(string(out), `"image_url"`) || strings.Contains(string(out), `"type":"image"`) || !strings.Contains(string(out), "[attachment "+tc.mime) {
t.Errorf("%s lost or mislabeled file: %s", protocol, out)
}
}
})
}
}
+11 -1
View File
@@ -20,6 +20,7 @@ type Kind string
const (
Text Kind = "text"
Image Kind = "image"
File Kind = "file"
ToolCall Kind = "tool_call"
ToolResult Kind = "tool_result"
Thinking Kind = "thinking"
@@ -31,7 +32,7 @@ type Part struct {
Kind Kind
Text string // text, thinking, or a tool result's output
// image
// image or file
MediaType string
Data string // base64
URL string
@@ -58,6 +59,15 @@ type Hit struct {
URL string `json:"url"`
}
// attachmentText is the fallback when a protocol cannot carry a Gemini file.
// Inline data has no URL to show and must not be relabeled as an image.
func attachmentText(p Part) string {
if p.URL != "" {
return "[attachment " + p.MediaType + ": " + p.URL + "]"
}
return "[attachment " + p.MediaType + "]"
}
// Message is one turn.
type Message struct {
Role string // user | assistant
+2
View File
@@ -284,6 +284,8 @@ func buildKiro(r *Request, model, profile string, thinking bool) []byte {
if p.Text != "" {
texts = append(texts, p.Text)
}
case File:
texts = append(texts, attachmentText(p))
case Image:
if p.Data != "" {
img := kiroImage{Format: kiroImageFormat(p.MediaType)}
+6
View File
@@ -198,6 +198,12 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {
t = "output_text"
}
content = append(content, map[string]any{"type": t, "text": p.Text})
case File:
t := "input_text"
if m.Role == "assistant" {
t = "output_text"
}
content = append(content, map[string]any{"type": t, "text": attachmentText(p)})
case Image:
if m.Role != "assistant" {
content = append(content, map[string]any{"type": "input_image", "image_url": dataURL(p)})