gateway: a recording a tool returns reaches Gemini as inlineData (Parlevent_ on X)
A Chat tool message's input_audio part was dropped: toolOutput read a tool result's text and images only, so after22f8db6c9carried a user's audio, a tool's audio still never reached a Gemini model (Parlevent_ on X, who found the cause). toolOutput now reads input_audio, from any inbound API's tool result (Chat's tool message; a Responses function_call_output that holds one), into the ToolResult's new Audio parts, with audioType's MIME type. - Gemini (Gemini API, Vertex AI, Code Assist, Antigravity's Gemini models): each recording follows the functionResponse as inlineData, as the tool's images do, and moves to the user turn after it on Vertex AI as they do. - Every other upstream (Chat, Responses, Messages, the Claude bridge, Antigravity's Claude models): the result's text ends with "[attachment audio/wav]", as a user's audio is told of; the bytes are never sent as an image, which those APIs would turn away with a 400. - Anthropic's tool_result has no audio block, so nothing changes for it. - tool_loop's resultSum counts the recordings, so two results that differ only in their audio aren't taken as a repeat. Not changed: a file a tool returns (an Anthropic document block, a Responses input_file) is still dropped from its result: #6703. Run (mica, mica-run; mote's load was over its cores): - TestChatToolAudioReachesGemini, TestToolAudioToldElsewhere: green. Broken by hand: with toolOutput's input_audio case off, both red; with the Gemini emitter's audio loop off, TestChatToolAudioReachesGemini red (no inlineData after the functionResponse). - go test ./internal/gateway -count=1 -timeout 45m: ok (862s), at base9afec644c- rebased onec97a4d7b(4 commits, none in internal/gateway): go vet ./internal/gateway and its Audio|ToolResult|Gemini tests: ok - go vet ./internal/gateway on darwin, GOOS=linux and GOOS=windows: ok - gofmt -l: clean Not tried: a real Gemini or Vertex AI request with a tool's audio.
This commit is contained in:
@@ -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":
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
+37
-10
@@ -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.
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user