diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 0982d12a1..84c15d1a1 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -246,8 +246,8 @@ func readAdvised(body []byte, clientMarks, facts, advised bool) (*Request, error msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID)}) break } - out, images := toolOutput(b.Content) - msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID), Text: out, Images: images, IsError: b.IsError, Loads: toolRefs(b.Content), block: true}) + out, images, audio := toolOutput(b.Content) + msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID), Text: out, Images: images, Audio: audio, IsError: b.IsError, Loads: toolRefs(b.Content), block: true}) case "thinking": msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: b.Thinking, Signature: b.Signature, block: true}) case "server_tool_use": diff --git a/internal/gateway/audio_input_test.go b/internal/gateway/audio_input_test.go index 8e52a9310..8d5dcab41 100644 --- a/internal/gateway/audio_input_test.go +++ b/internal/gateway/audio_input_test.go @@ -34,3 +34,55 @@ func TestAudioType(t *testing.T) { } } } + +// toolAudioChat is a Chat conversation whose tool message returns a +// recording, as Parlevent_'s client sends one: text and input_audio parts. +func toolAudioChat(model, audio string) string { + return `{"model":"` + model + `","messages":[` + + `{"role":"user","content":"听一下录音"},` + + `{"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"record","arguments":"{}"}}]},` + + `{"role":"tool","tool_call_id":"call_1","content":[{"type":"text","text":"recorded"},{"type":"input_audio","input_audio":{"data":"` + audio + `","format":"wav"}}]}]}` +} + +// A recording a tool returned in a Chat tool message reaches a Gemini +// upstream as inlineData after the functionResponse, as its images do. +// toolOutput read only text and images, so it was dropped (Parlevent_ on +// X, after TestChatAudioReachesGemini's fix for a user's audio). +func TestChatToolAudioReachesGemini(t *testing.T) { + fresh(t) + noVision(t) + 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") + s := New() + const audio = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA=" + rec := serveVideo(s, "/v1/chat/completions", toolAudioChat("gem/u", audio)) + bodies, _ := gem.sent() + if rec.Code != 200 || len(bodies) != 1 { + t.Fatalf("%d %s; upstream %v", rec.Code, rec.Body.String(), bodies) + } + b := bodies[0] + resp, inline := strings.Index(b, `"functionResponse"`), strings.Index(b, `{"inlineData":{"data":"`+audio+`","mimeType":"audio/wav"}}`) + if resp < 0 || inline < resp { + t.Errorf("the tool's audio isn't inlineData after its response: %s", b) + } +} + +// Every other upstream is told of the recording in the result's text and +// is never handed it as an image, which Chat, Responses and Messages would +// turn away with a 400. +func TestToolAudioToldElsewhere(t *testing.T) { + const audio = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA=" + r, err := parseChat([]byte(toolAudioChat("m", audio))) + if err != nil { + t.Fatal(err) + } + for name, body := range map[string][]byte{ + "chat": buildChat(r, "m", "api.example.com", false), + "responses": buildResponses(r, "m", "api.example.com", false), + "messages": buildAnthropic(r, "m"), + } { + if s := string(body); strings.Contains(s, audio) || !strings.Contains(s, `recorded\n[attachment audio/wav]`) { + t.Errorf("%s: %s", name, s) + } + } +} diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index eae2ba421..9a7d91c96 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -178,8 +178,8 @@ func readChat(body []byte, facts bool) (*Request, error) { r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: m.ToolCallID}}}) continue } - out, images := toolOutput(m.Content) - r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: m.ToolCallID, Text: out, Images: images}}}) + out, images, audio := toolOutput(m.Content) + r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: m.ToolCallID, Text: out, Images: images, Audio: audio}}}) } } r.System = strings.Join(sys, "\n\n") diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go index 0786acfc7..6d90b0e56 100644 --- a/internal/gateway/codeassist.go +++ b/internal/gateway/codeassist.go @@ -663,6 +663,17 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte { parts = append(parts, im) } } + // the recordings it returned follow as its images do; a + // Claude model on Antigravity hears none, and has the + // note toolOutput ended the text with + if !(ag && claude) { + for _, a := range p.Audio { + if a.Data != "" { + toolImage[len(parts)] = true + parts = append(parts, geminiInline(a.MediaType, a.Data)) + } + } + } } // thinking isn't sent back: its signatures belong to whoever // made them, and Google turns away ones it didn't diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index ea056683d..58bcb276e 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -58,6 +58,12 @@ type Part struct { IsError bool Images []Part // the images the tool returned beside its text Standalone map[string]any // native Responses notification with no call ID + // Audio is the recordings the tool returned (a Chat tool message's + // input_audio parts), as File parts with an audio/* type: a Gemini + // upstream is given them inline after the response, as its images; + // every other upstream is told of them in the result's text, which + // toolOutput already ends with a note for each + Audio []Part // Loads are the tools a tool's result loads, by name: Claude Code's // ToolSearch answers with tool_reference blocks naming the deferred // tools it found (#2660) @@ -977,11 +983,15 @@ func stringOrText(raw json.RawMessage) string { } // toolOutput reads a tool's result: its text, as stringOrText reads it, -// and the images in it. Anthropic's tool_result holds image blocks, a -// Responses function_call_output input_image parts and a Chat tool message, -// from clients that send them, image_url parts. An image named only by a -// vendor's file id has nothing to carry and is left out. -func toolOutput(raw json.RawMessage) (string, []Part) { +// the images in it and the recordings. Anthropic's tool_result holds image +// blocks, a Responses function_call_output input_image parts and a Chat +// tool message, from clients that send them, image_url and input_audio +// parts. An image named only by a vendor's file id has nothing to carry and +// is left out. Each recording is also told of at the end of the text +// ("[attachment audio/wav]", as a Chat user's input_audio is told of to an +// upstream that can't hear it), so an upstream given the text alone knows +// the tool returned one; a Gemini upstream is given the recording too. +func toolOutput(raw json.RawMessage) (string, []Part, []Part) { text := stringOrText(raw) var blocks []struct { Type string `json:"type"` @@ -990,13 +1000,17 @@ func toolOutput(raw json.RawMessage) (string, []Part) { Data string `json:"data"` URL string `json:"url"` } `json:"source"` - ImageURL json.RawMessage `json:"image_url"` - Detail string `json:"detail"` // a Responses input_image's + ImageURL json.RawMessage `json:"image_url"` + Detail string `json:"detail"` // a Responses input_image's + InputAudio struct { + Data string `json:"data"` + Format string `json:"format"` + } `json:"input_audio"` } if len(raw) == 0 || raw[0] != '[' || decodeJSON(raw, &blocks) != nil { - return text, nil + return text, nil, nil } - var images []Part + var images, audio []Part for _, b := range blocks { switch b.Type { case "image": @@ -1021,9 +1035,22 @@ func toolOutput(raw json.RawMessage) (string, []Part) { im.Detail = detail images = append(images, im) } + case "input_audio": + // a tool's recording, as a Chat user's input_audio is read + // (chatParts): left out before, so Gemini answered without + // it (Parlevent_ on X) + if b.InputAudio.Data != "" { + audio = append(audio, Part{Kind: File, MediaType: audioType(b.InputAudio.Format), Data: b.InputAudio.Data}) + } } } - return text, images + for _, a := range audio { + if text != "" { + text += "\n" + } + text += attachmentText(a) + } + return text, images, audio } // effortOf normalises the reasoning effort names the APIs use. diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 31b5d4c01..f4755ee71 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -470,8 +470,8 @@ func readResponsesFor(body []byte, facts, keepInstructions bool) (*Request, erro case (it.Type == "function_call_output" || it.Type == "custom_tool_call_output") && facts: r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: it.CallID}}}) case it.Type == "function_call_output" || it.Type == "custom_tool_call_output": - out, images := toolOutput(it.Output) - part := Part{Kind: ToolResult, CallID: it.CallID, Text: out, Images: images} + out, images, audio := toolOutput(it.Output) + part := Part{Kind: ToolResult, CallID: it.CallID, Text: out, Images: images, Audio: audio} if it.CallID == "" { // Native account requests may still need translation to // collect a streamed response for a non-streaming client. @@ -907,7 +907,9 @@ func orphanedToolOutputs(body []byte) []byte { out = append(out, raw) continue } - text, images := toolOutput(item.Output) + // a recording is told of in the text: a Chat upstream's user + // message takes no audio from magpie (chat.go's File) + text, images, _ := toolOutput(item.Output) content := []map[string]any{} if text != "" { content = append(content, map[string]any{"type": "input_text", "text": text}) diff --git a/internal/gateway/tool_loop.go b/internal/gateway/tool_loop.go index 3cb442943..8e0750527 100644 --- a/internal/gateway/tool_loop.go +++ b/internal/gateway/tool_loop.go @@ -335,7 +335,7 @@ func resultSum(p Part) string { b.WriteString("error\x00") } b.WriteString(steadyResult(p.Text)) - for _, im := range p.Images { + for _, im := range append(slices.Clone(p.Images), p.Audio...) { b.WriteString("\x00" + im.MediaType + im.Data + im.URL) } return b.String()