fix: preserve multimodal Responses tool outputs

This commit is contained in:
大魔王 committed 2026-07-20 02:48:31 +08:00
1 parent d74b153966
commit fb5932bdcf
10 files changed
+1049 -12

No files matched your search

@@ -0,0 +1,466 @@
package gateway
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log/slog"
"strings"
)
type responseMediaSummary struct {
InputImages int64
ImageBytes int64
ContentArrays int64
TextBytes int64
}
func (summary *responseMediaSummary) add(value responseMediaSummary) {
summary.InputImages += value.InputImages
summary.ImageBytes += value.ImageBytes
summary.ContentArrays += value.ContentArrays
summary.TextBytes += value.TextBytes
}
type mediaJSONKind uint8
const (
mediaJSONOther mediaJSONKind = iota
mediaJSONString
mediaJSONObjectKind
mediaJSONArrayKind
)
type mediaJSONValue struct {
kind mediaJSONKind
stringBytes int64
object *mediaJSONObject
array *mediaJSONArray
}
type mediaJSONObject struct {
typeName string
role string
textBytes int64
imageURLBytes int64
urlBytes int64
dataBytes int64
sourceType string
sourceBytes int64
content *mediaJSONValue
output *mediaJSONValue
input *mediaJSONValue
messages *mediaJSONValue
}
type mediaJSONArray struct {
contentItems responseMediaSummary
inputItems responseMediaSummary
messageItems responseMediaSummary
}
func summarizeResponseMedia(body []byte) (responseMediaSummary, error) {
decoder := json.NewDecoder(bytes.NewReader(body))
value, err := decodeMediaJSONValue(decoder)
if err != nil {
return responseMediaSummary{}, err
}
if token, err := decoder.Token(); err != io.EOF {
if err == nil {
return responseMediaSummary{}, fmt.Errorf("unexpected trailing JSON token %v", token)
}
return responseMediaSummary{}, err
}
if value.object == nil {
return responseMediaSummary{}, nil
}
var summary responseMediaSummary
summary.add(statsForRootInput(value.object.input))
summary.add(statsForMessages(value.object.messages))
return summary, nil
}
func logResponseMediaSummary(logger *slog.Logger, requestID string, summary responseMediaSummary) {
if logger == nil || (summary.InputImages == 0 && summary.ContentArrays == 0) {
return
}
logger.Info(
"request_media_input_summary",
"request_id", requestID,
"media_input_images", summary.InputImages,
"media_input_image_bytes", summary.ImageBytes,
"media_content_arrays", summary.ContentArrays,
"media_text_bytes", summary.TextBytes,
)
}
func decodeMediaJSONValue(decoder *json.Decoder) (*mediaJSONValue, error) {
token, err := decoder.Token()
if err != nil {
return nil, err
}
switch value := token.(type) {
case json.Delim:
switch value {
case '{':
object, err := decodeMediaJSONObject(decoder)
return &mediaJSONValue{kind: mediaJSONObjectKind, object: object}, err
case '[':
array, err := decodeMediaJSONArray(decoder)
return &mediaJSONValue{kind: mediaJSONArrayKind, array: array}, err
default:
return nil, fmt.Errorf("unexpected JSON delimiter %q", value)
}
case string:
return &mediaJSONValue{kind: mediaJSONString, stringBytes: int64(len(value))}, nil
default:
return &mediaJSONValue{kind: mediaJSONOther}, nil
}
}
func decodeMediaJSONObject(decoder *json.Decoder) (*mediaJSONObject, error) {
object := &mediaJSONObject{}
for decoder.More() {
keyToken, err := decoder.Token()
if err != nil {
return nil, err
}
key, ok := keyToken.(string)
if !ok {
return nil, fmt.Errorf("JSON object key is not a string")
}
switch key {
case "type":
object.typeName, err = decodeMediaShortString(decoder)
case "role":
object.role, err = decodeMediaShortString(decoder)
case "text":
object.textBytes, err = decodeMediaStringBytes(decoder)
case "image_url":
object.imageURLBytes, err = decodeMediaImageReference(decoder)
case "url":
object.urlBytes, err = decodeMediaDataURIBytes(decoder)
case "data":
object.dataBytes, err = decodeMediaBase64Bytes(decoder)
case "source":
var value *mediaJSONValue
value, err = decodeMediaJSONValue(decoder)
if value != nil && value.object != nil {
object.sourceType = value.object.typeName
object.sourceBytes = value.object.dataBytes
}
case "content":
object.content, err = decodeMediaJSONValue(decoder)
case "output":
object.output, err = decodeMediaJSONValue(decoder)
case "input":
object.input, err = decodeMediaJSONValue(decoder)
case "messages":
object.messages, err = decodeMediaJSONValue(decoder)
default:
err = skipMediaJSONValue(decoder)
}
if err != nil {
return nil, err
}
}
if token, err := decoder.Token(); err != nil {
return nil, err
} else if token != json.Delim('}') {
return nil, fmt.Errorf("unexpected JSON object terminator %v", token)
}
return object, nil
}
func decodeMediaJSONArray(decoder *json.Decoder) (*mediaJSONArray, error) {
array := &mediaJSONArray{}
for decoder.More() {
value, err := decodeMediaJSONValue(decoder)
if err != nil {
return nil, err
}
array.contentItems.add(statsForContentBlock(value))
array.inputItems.add(statsForInputItem(value))
array.messageItems.add(statsForMessage(value))
}
if token, err := decoder.Token(); err != nil {
return nil, err
} else if token != json.Delim(']') {
return nil, fmt.Errorf("unexpected JSON array terminator %v", token)
}
return array, nil
}
func decodeMediaShortString(decoder *json.Decoder) (string, error) {
token, err := decoder.Token()
if err != nil {
return "", err
}
value, ok := token.(string)
if !ok {
if delimiter, ok := token.(json.Delim); ok {
if err := skipMediaJSONContainer(decoder, delimiter); err != nil {
return "", err
}
}
return "", nil
}
if len(value) > 64 {
return "", nil
}
return value, nil
}
func decodeMediaStringBytes(decoder *json.Decoder) (int64, error) {
token, err := decoder.Token()
if err != nil {
return 0, err
}
if value, ok := token.(string); ok {
return int64(len(value)), nil
}
if delimiter, ok := token.(json.Delim); ok {
return 0, skipMediaJSONContainer(decoder, delimiter)
}
return 0, nil
}
func decodeMediaDataURIBytes(decoder *json.Decoder) (int64, error) {
token, err := decoder.Token()
if err != nil {
return 0, err
}
if value, ok := token.(string); ok {
return dataURIImageBytes(value), nil
}
if delimiter, ok := token.(json.Delim); ok {
return 0, skipMediaJSONContainer(decoder, delimiter)
}
return 0, nil
}
func decodeMediaBase64Bytes(decoder *json.Decoder) (int64, error) {
token, err := decoder.Token()
if err != nil {
return 0, err
}
if value, ok := token.(string); ok {
return decodedBase64Bytes(value), nil
}
if delimiter, ok := token.(json.Delim); ok {
return 0, skipMediaJSONContainer(decoder, delimiter)
}
return 0, nil
}
func decodeMediaImageReference(decoder *json.Decoder) (int64, error) {
token, err := decoder.Token()
if err != nil {
return 0, err
}
if value, ok := token.(string); ok {
return dataURIImageBytes(value), nil
}
if delimiter, ok := token.(json.Delim); ok {
if delimiter == '{' {
object, err := decodeMediaJSONObject(decoder)
if err != nil {
return 0, err
}
return max(object.urlBytes, object.imageURLBytes), nil
}
return 0, skipMediaJSONContainer(decoder, delimiter)
}
return 0, nil
}
func skipMediaJSONValue(decoder *json.Decoder) error {
token, err := decoder.Token()
if err != nil {
return err
}
if delimiter, ok := token.(json.Delim); ok {
return skipMediaJSONContainer(decoder, delimiter)
}
return nil
}
func skipMediaJSONContainer(decoder *json.Decoder, opening json.Delim) error {
if opening != '{' && opening != '[' {
return fmt.Errorf("unexpected JSON delimiter %q", opening)
}
for decoder.More() {
if opening == '{' {
if _, err := decoder.Token(); err != nil {
return err
}
}
if err := skipMediaJSONValue(decoder); err != nil {
return err
}
}
_, err := decoder.Token()
return err
}
func statsForRootInput(value *mediaJSONValue) responseMediaSummary {
if value == nil {
return responseMediaSummary{}
}
if value.kind == mediaJSONString {
return responseMediaSummary{TextBytes: value.stringBytes}
}
if value.array != nil {
return value.array.inputItems
}
return statsForInputItem(value)
}
func statsForMessages(value *mediaJSONValue) responseMediaSummary {
if value == nil {
return responseMediaSummary{}
}
if value.array != nil {
return value.array.messageItems
}
return statsForMessage(value)
}
func statsForInputItem(value *mediaJSONValue) responseMediaSummary {
if value == nil {
return responseMediaSummary{}
}
if value.kind == mediaJSONString {
return responseMediaSummary{TextBytes: value.stringBytes}
}
if value.object == nil {
return responseMediaSummary{}
}
switch value.object.typeName {
case "message":
return statsForContentField(value.object.content)
case "function_call_output":
return statsForContentField(value.object.output)
case "input_text", "input_image", "image_url", "image", "text", "tool_result":
return statsForContentBlock(value)
default:
if value.object.role != "" {
return statsForContentField(value.object.content)
}
return responseMediaSummary{}
}
}
func statsForMessage(value *mediaJSONValue) responseMediaSummary {
if value == nil || value.object == nil {
return responseMediaSummary{}
}
if value.object.role == "" && value.object.typeName != "message" {
return responseMediaSummary{}
}
return statsForContentField(value.object.content)
}
func statsForContentField(value *mediaJSONValue) responseMediaSummary {
if value == nil {
return responseMediaSummary{}
}
if value.kind == mediaJSONString {
return responseMediaSummary{TextBytes: value.stringBytes}
}
if value.array == nil {
return responseMediaSummary{}
}
summary := value.array.contentItems
summary.ContentArrays++
return summary
}
func statsForContentBlock(value *mediaJSONValue) responseMediaSummary {
if value == nil {
return responseMediaSummary{}
}
if value.kind == mediaJSONString {
return responseMediaSummary{TextBytes: value.stringBytes}
}
if value.object == nil {
return responseMediaSummary{}
}
object := value.object
switch object.typeName {
case "input_text", "text", "output_text":
return responseMediaSummary{TextBytes: object.textBytes}
case "input_image":
return responseMediaSummary{InputImages: 1, ImageBytes: object.imageURLBytes}
case "image_url":
return responseMediaSummary{InputImages: 1, ImageBytes: max(object.imageURLBytes, object.urlBytes)}
case "image":
imageBytes := object.imageURLBytes
if object.sourceType == "base64" {
imageBytes = object.sourceBytes
}
return responseMediaSummary{InputImages: 1, ImageBytes: imageBytes}
case "tool_result":
return statsForContentField(object.content)
default:
return responseMediaSummary{}
}
}
func dataURIImageBytes(value string) int64 {
comma := strings.IndexByte(value, ',')
if comma <= 0 {
return 0
}
header := strings.ToLower(value[:comma])
if !strings.HasPrefix(header, "data:image/") || !strings.Contains(header, ";base64") {
return 0
}
return decodedBase64Bytes(value[comma+1:])
}
func decodedBase64Bytes(value string) int64 {
var symbols int64
var padding int64
seenPadding := false
for index := 0; index < len(value); index++ {
character := value[index]
switch {
case character == ' ' || character == '\n' || character == '\r' || character == '\t':
continue
case character == '=':
seenPadding = true
padding++
if padding > 2 {
return 0
}
case (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z') ||
(character >= '0' && character <= '9') || character == '+' || character == '/' || character == '-' || character == '_':
if seenPadding {
return 0
}
default:
return 0
}
symbols++
}
if symbols == 0 {
return 0
}
if padding > 0 && symbols%4 != 0 {
return 0
}
switch remainder := symbols % 4; remainder {
case 0:
return symbols/4*3 - padding
case 2:
return symbols/4*3 + 1
case 3:
return symbols/4*3 + 2
default:
return 0
}
}
@@ -0,0 +1,104 @@
package gateway
import (
"bytes"
"log/slog"
"strings"
"testing"
)
func TestSummarizeResponseMediaScansMessagesAndFunctionOutputs(t *testing.T) {
summary, err := summarizeResponseMedia([]byte(`{
"input":[
{"type":"message","role":"user","content":[
{"type":"input_text","text":"hello"},
{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}
]},
{"type":"function_call_output","call_id":"call_1","output":[
{"type":"input_text","text":"tool"},
{"type":"input_image","image_url":"data:image/jpeg;base64,QUJD"},
{"type":"input_image","file_id":"file_1"}
]}
]
}`))
if err != nil {
t.Fatal(err)
}
want := responseMediaSummary{InputImages: 3, ImageBytes: 8, ContentArrays: 2, TextBytes: 9}
if summary != want {
t.Fatalf("summary = %#v, want %#v", summary, want)
}
}
func TestSummarizeResponseMediaSupportsChatAndAnthropicBlocks(t *testing.T) {
summary, err := summarizeResponseMedia([]byte(`{
"messages":[
{"role":"user","content":[
{"type":"text","text":"chat"},
{"type":"image_url","image_url":{"url":"data:image/webp;base64,QUJDRA=="}}
]},
{"role":"user","content":[
{"type":"tool_result","tool_use_id":"tool_1","content":[
{"type":"text","text":"anthropic"},
{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}
]}
]}
]
}`))
if err != nil {
t.Fatal(err)
}
want := responseMediaSummary{InputImages: 2, ImageBytes: 9, ContentArrays: 3, TextBytes: 13}
if summary != want {
t.Fatalf("summary = %#v, want %#v", summary, want)
}
}
func TestSummarizeResponseMediaDoesNotInterpretArbitraryImageContent(t *testing.T) {
summary, err := summarizeResponseMedia([]byte(`{
"input":[{"type":"function_call_output","call_id":"call_1","output":{"ImageContent":{"data":"aGVsbG8="}}}]
}`))
if err != nil {
t.Fatal(err)
}
if summary != (responseMediaSummary{}) {
t.Fatalf("summary = %#v", summary)
}
}
func TestResponseMediaSummaryLogContainsOnlyMetadata(t *testing.T) {
var output bytes.Buffer
logger := slog.New(slog.NewTextHandler(&output, nil))
logResponseMediaSummary(logger, "req-media", responseMediaSummary{
InputImages: 42, ImageBytes: 33_030_144, ContentArrays: 42, TextBytes: 840,
})
logged := output.String()
for _, expected := range []string{
"request_media_input_summary", "request_id=req-media", "media_input_images=42",
"media_input_image_bytes=33030144", "media_content_arrays=42", "media_text_bytes=840",
} {
if !strings.Contains(logged, expected) {
t.Fatalf("log missing %q: %s", expected, logged)
}
}
for _, forbidden := range []string{"base64", "Authorization", "Cookie", "account", `C:\\`, `D:\\`, `E:\\`} {
if strings.Contains(logged, forbidden) {
t.Fatalf("log contains forbidden value %q: %s", forbidden, logged)
}
}
}
func TestDecodedBase64Bytes(t *testing.T) {
for encoded, want := range map[string]int64{
"aGVsbG8=": 5,
"QUJD": 3,
"QUI": 2,
"QQ": 1,
"bad!": 0,
"QQ=A": 0,
} {
if got := decodedBase64Bytes(encoded); got != want {
t.Fatalf("decodedBase64Bytes(%q) = %d, want %d", encoded, got, want)
}
}
}
@@ -422,10 +422,13 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
if usageKind, _ := s.providers.UsageKind(route.Provider); usageKind == provider.UsageEstimated {
usageSource = audit.UsageSourceEstimated
}
mediaSummary, _ := summarizeResponseMedia(input.Body)
logResponseMediaSummary(s.logger, input.RequestID, mediaSummary)
auditBase := audit.Record{
EventID: eventID, RequestID: input.RequestID, ClientKeyID: input.ClientKey.ID, ClientKeyName: input.ClientKey.Name,
ModelRouteID: route.ID, ModelPublicID: publicModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
Provider: string(route.Provider), Operation: operation, UsageSource: usageSource, Streaming: input.Streaming,
MediaInputImages: mediaSummary.InputImages,
}
if errors.Is(routeErr, clientkeyapp.ErrModelNotAllowed) {
record := auditBase
@@ -293,11 +293,25 @@ func normalizeShellCallOutputInput(item map[string]any, param string) (map[strin
}
func normalizeFunctionCallOutputInput(item map[string]any, param string) (map[string]any, error) {
return normalizeFunctionLikeCallOutputInput(item, param, true)
}
func normalizeCustomToolCallOutputInput(item map[string]any, param string) (map[string]any, error) {
return normalizeFunctionLikeCallOutputInput(item, param, false)
}
func normalizeFunctionLikeCallOutputInput(item map[string]any, param string, allowContentBlocks bool) (map[string]any, error) {
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
output, err := encodeToolOutput(item["output"], param+".output")
output := item["output"]
var err error
if blocks, ok := output.([]any); ok && allowContentBlocks {
output, err = normalizeFunctionCallOutputBlocks(blocks, param+".output")
} else {
output, err = encodeToolOutput(output, param+".output")
}
if err != nil {
return nil, err
}
@@ -305,6 +319,97 @@ func normalizeFunctionCallOutputInput(item map[string]any, param string) (map[st
return map[string]any{"type": "function_call_output", "call_id": callID, "output": output}, nil
}
func normalizeFunctionCallOutputBlocks(blocks []any, param string) ([]any, error) {
normalized := make([]any, 0, len(blocks))
for index, raw := range blocks {
blockParam := fmt.Sprintf("%s[%d]", param, index)
block, ok := raw.(map[string]any)
if !ok {
return nil, &responsesRequestError{Message: blockParam + " 必须是对象", Param: blockParam, Code: "invalid_parameter"}
}
blockType := strings.TrimSpace(stringField(block, "type"))
if blockType == "" {
return nil, &responsesRequestError{Message: blockParam + ".type 不能为空", Param: blockParam + ".type", Code: "invalid_parameter"}
}
switch blockType {
case "input_text":
text, ok := block["text"].(string)
if !ok {
return nil, &responsesRequestError{Message: blockParam + ".text 必须是字符串", Param: blockParam + ".text", Code: "invalid_parameter"}
}
normalized = append(normalized, map[string]any{"type": "input_text", "text": text})
case "input_image":
converted, err := normalizeFunctionCallOutputImageBlock(block, blockParam)
if err != nil {
return nil, err
}
normalized = append(normalized, converted)
case "input_file":
converted, err := normalizeFunctionCallOutputFileBlock(block, blockParam)
if err != nil {
return nil, err
}
normalized = append(normalized, converted)
default:
return nil, &responsesRequestError{Message: "Grok Build 0.2.103 不支持该 function_call_output.output 类型", Param: blockParam + ".type", Code: "unsupported_parameter"}
}
}
return normalized, nil
}
func normalizeFunctionCallOutputImageBlock(block map[string]any, param string) (map[string]any, error) {
detail, ok := block["detail"].(string)
if !ok {
return nil, &responsesRequestError{Message: param + ".detail 必须是字符串", Param: param + ".detail", Code: "invalid_parameter"}
}
switch detail {
case "auto", "low", "high":
default:
return nil, &responsesRequestError{Message: param + ".detail 只支持 auto、low 或 high", Param: param + ".detail", Code: "invalid_parameter"}
}
_, hasImageURL, err := nonEmptyContentBlockString(block, "image_url", param)
if err != nil {
return nil, err
}
_, hasFileID, err := nonEmptyContentBlockString(block, "file_id", param)
if err != nil {
return nil, err
}
if !hasImageURL && !hasFileID {
return nil, &responsesRequestError{Message: param + ".image_url 或 .file_id 至少需要一个", Param: param + ".image_url", Code: "invalid_parameter"}
}
return normalizeInputImagePart(block), nil
}
func normalizeFunctionCallOutputFileBlock(block map[string]any, param string) (map[string]any, error) {
hasSource := false
for _, key := range []string{"file_data", "file_id", "file_url", "filename"} {
_, exists, err := nonEmptyContentBlockString(block, key, param)
if err != nil {
return nil, err
}
if key != "filename" && exists {
hasSource = true
}
}
if !hasSource {
return nil, &responsesRequestError{Message: param + " 至少需要 file_data、file_id 或 file_url 之一", Param: param + ".file_data", Code: "invalid_parameter"}
}
return normalizeInputFilePart(block), nil
}
func nonEmptyContentBlockString(block map[string]any, key, param string) (string, bool, error) {
raw, exists := block[key]
if !exists || raw == nil {
return "", false, nil
}
value, ok := raw.(string)
if !ok || strings.TrimSpace(value) == "" {
return "", false, &responsesRequestError{Message: param + "." + key + " 必须是非空字符串", Param: param + "." + key, Code: "invalid_parameter"}
}
return value, true, nil
}
func encodeToolOutput(value any, param string) (string, error) {
switch typed := value.(type) {
case nil:
@@ -121,6 +121,136 @@ func TestFunctionCallOutputHistoryEncodesStructuredOutput(t *testing.T) {
}
}
func TestFunctionCallOutputHistoryPreservesContentBlocks(t *testing.T) {
normalized, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","tools":[{"type":"function","name":"read_file","parameters":{"type":"object"}}],"input":[
{"type":"function_call_output","call_id":"call_1","status":"completed","output":[
{"type":"input_text","text":"Read image file: screenshot.png"},
{"type":"input_image","detail":"auto","image_url":"data:image/png;base64,aGVsbG8="},
{"type":"input_image","detail":"high","file_id":"file_image_2"},
{"type":"input_file","file_id":"file_document_1","filename":"notes.txt"}
]}
]
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
var request map[string]any
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
item := request["input"].([]any)[0].(map[string]any)
output, ok := item["output"].([]any)
if !ok || len(output) != 4 {
t.Fatalf("function output history = %#v", item)
}
text := output[0].(map[string]any)
firstImage := output[1].(map[string]any)
secondImage := output[2].(map[string]any)
file := output[3].(map[string]any)
if text["type"] != "input_text" || text["text"] != "Read image file: screenshot.png" ||
firstImage["type"] != "input_image" || firstImage["detail"] != "auto" ||
firstImage["image_url"] != "data:image/png;base64,aGVsbG8=" ||
secondImage["type"] != "input_image" || secondImage["detail"] != "high" || secondImage["file_id"] != "file_image_2" ||
file["type"] != "input_file" || file["file_id"] != "file_document_1" || file["filename"] != "notes.txt" ||
item["status"] != nil {
t.Fatalf("function output history = %#v", item)
}
}
func TestFunctionCallOutputHistoryRejectsInvalidContentBlocks(t *testing.T) {
tests := []struct {
name string
output string
wantParam string
wantCode string
}{
{name: "non_object", output: `["not an object"]`, wantParam: "input[0].output[0]", wantCode: "invalid_parameter"},
{name: "missing_type", output: `[{"text":"missing type"}]`, wantParam: "input[0].output[0].type", wantCode: "invalid_parameter"},
{name: "missing_text", output: `[{"type":"input_text"}]`, wantParam: "input[0].output[0].text", wantCode: "invalid_parameter"},
{name: "missing_image_detail", output: `[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]`, wantParam: "input[0].output[0].detail", wantCode: "invalid_parameter"},
{name: "missing_image_source", output: `[{"type":"input_image","detail":"auto"}]`, wantParam: "input[0].output[0].image_url", wantCode: "invalid_parameter"},
{name: "invalid_image_detail", output: `[{"type":"input_image","detail":"original","image_url":"data:image/png;base64,AA=="}]`, wantParam: "input[0].output[0].detail", wantCode: "invalid_parameter"},
{name: "missing_file_source", output: `[{"type":"input_file","filename":"empty.txt"}]`, wantParam: "input[0].output[0].file_data", wantCode: "invalid_parameter"},
{name: "unknown_type", output: `[{"type":"input_audio","data":"AA=="}]`, wantParam: "input[0].output[0].type", wantCode: "unsupported_parameter"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
body := []byte(`{"model":"public","input":[{"type":"function_call_output","call_id":"call_1","output":` + test.output + `}]}`)
_, _, err := normalizeResponsesRequest(body, "grok-4.5")
requestErr, ok := err.(*responsesRequestError)
if !ok || requestErr.Param != test.wantParam || requestErr.Code != test.wantCode {
t.Fatalf("error = %#v", err)
}
})
}
}
func TestCustomToolCallOutputHistoryStillEncodesArrayAsString(t *testing.T) {
normalized, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":[{"type":"custom_tool_call_output","call_id":"call_1","output":[
{"type":"input_text","text":"custom output"},
{"type":"input_image","detail":"auto","image_url":"data:image/png;base64,AA=="}
]}]
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
var request map[string]any
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
item := request["input"].([]any)[0].(map[string]any)
output, ok := item["output"].(string)
if item["type"] != "function_call_output" || !ok || !strings.Contains(output, `"type":"input_image"`) {
t.Fatalf("custom tool output history = %#v", item)
}
}
func TestFunctionCallOutputHistoryPreservesFortyTwoImagesAtThirtyTwoMiB(t *testing.T) {
const (
imageCount = 42
totalPayloadSize = 32 << 20
)
perImagePayloadSize := (totalPayloadSize / imageCount) / 4 * 4
imageURL := "data:image/png;base64," + strings.Repeat("A", perImagePayloadSize)
blocks := make([]any, 0, imageCount)
for range imageCount {
blocks = append(blocks, map[string]any{"type": "input_image", "detail": "auto", "image_url": imageURL})
}
body, err := json.Marshal(map[string]any{
"model": "public",
"input": []any{map[string]any{
"type": "function_call_output", "call_id": "call_images", "output": blocks,
}},
})
if err != nil {
t.Fatal(err)
}
if len(body) < totalPayloadSize {
t.Fatalf("fixture size = %d", len(body))
}
normalized, _, err := normalizeResponsesRequest(body, "grok-4.5")
if err != nil {
t.Fatal(err)
}
var request map[string]any
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
item := request["input"].([]any)[0].(map[string]any)
output, ok := item["output"].([]any)
if !ok || len(output) != imageCount {
t.Fatalf("output type = %T, length = %d", item["output"], len(output))
}
for _, index := range []int{0, imageCount - 1} {
image := output[index].(map[string]any)
if image["type"] != "input_image" || image["detail"] != "auto" || image["image_url"] != imageURL {
t.Fatalf("output[%d] was not preserved", index)
}
}
}
func TestAssistantOutputMessageHistoryUsesEasyMessageText(t *testing.T) {
normalized, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":[
@@ -121,7 +121,7 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, []
c.changed = true
rewritten = append(rewritten, converted)
case "custom_tool_call_output":
converted, err := normalizeFunctionCallOutputInput(item, param)
converted, err := normalizeCustomToolCallOutputInput(item, param)
if err != nil {
return nil, nil, nil, err
}
@@ -0,0 +1,133 @@
package cli
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
"github.com/chenyme/grok2api/backend/internal/infra/security"
)
func TestForwardResponseCapturesNativeMultimodalFunctionOutput(t *testing.T) {
var captured map[string]any
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
t.Fatal(err)
}
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(key))
if err != nil {
t.Fatal(err)
}
encrypted, err := cipher.Encrypt("access-token")
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1"}, cipher)
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
body, err := io.ReadAll(request.Body)
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(body, &captured); err != nil {
t.Fatal(err)
}
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"resp_1"}`)), Request: request}, nil
})
response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
Credential: account.Credential{Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", Operation: conversation.OperationResponses, NormalizeBody: true,
Body: []byte(`{"model":"public","input":[{"type":"function_call_output","call_id":"call_1","output":[{"type":"input_text","text":"read"},{"type":"input_image","detail":"auto","image_url":"data:image/png;base64,AA=="}]}]}`),
})
if err != nil {
t.Fatal(err)
}
_ = response.Body.Close()
assertWireFunctionOutputArray(t, captured)
}
func TestForwardResponseCapturesChatAndAnthropicMultimodalToolResults(t *testing.T) {
tests := []struct {
name string
operation string
body string
}{
{
name: "chat",
operation: conversation.OperationChat,
body: `{"model":"public","messages":[{"role":"assistant","tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{}"}}]},{"role":"tool","tool_call_id":"call_1","content":[{"type":"text","text":"read"},{"type":"image_url","image_url":"data:image/png;base64,AA=="}]}]}`,
},
{
name: "anthropic",
operation: conversation.OperationMessages,
body: `{"model":"public","max_tokens":64,"tools":[{"name":"read_file","input_schema":{"type":"object"}}],"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"read_file","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":[{"type":"text","text":"read"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AA=="}}]}]}]}`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var captured map[string]any
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
t.Fatal(err)
}
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(key))
if err != nil {
t.Fatal(err)
}
encrypted, err := cipher.Encrypt("access-token")
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1"}, cipher)
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
body, err := io.ReadAll(request.Body)
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(body, &captured); err != nil {
t.Fatal(err)
}
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"resp_1"}`)), Request: request}, nil
})
response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
Credential: account.Credential{Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", Operation: test.operation, NormalizeBody: true, Body: []byte(test.body),
})
if err != nil {
t.Fatal(err)
}
_ = response.Body.Close()
assertWireFunctionOutputArray(t, captured)
})
}
}
func assertWireFunctionOutputArray(t *testing.T, captured map[string]any) {
t.Helper()
items, ok := captured["input"].([]any)
if !ok || len(items) == 0 {
t.Fatalf("captured input = %#v", captured["input"])
}
for _, raw := range items {
item, ok := raw.(map[string]any)
if !ok || item["type"] != "function_call_output" {
continue
}
output, ok := item["output"].([]any)
if !ok || len(output) != 2 {
t.Fatalf("function output was stringified: %#v", item["output"])
}
image := output[1].(map[string]any)
if image["type"] != "input_image" || image["image_url"] != "data:image/png;base64,AA==" {
t.Fatalf("image wire = %#v", image)
}
return
}
t.Fatalf("function_call_output not found in %#v", items)
}
@@ -130,7 +130,7 @@ func convertChatMessages(messages []chatMessage) ([]any, error) {
if strings.TrimSpace(message.ToolCallID) == "" {
return nil, errors.New("tool 消息缺少 tool_call_id")
}
output, err := contentAsText(message.Content)
output, err := convertChatToolOutput(message.Content)
if err != nil {
return nil, err
}
@@ -166,11 +166,11 @@ func convertChatContent(raw json.RawMessage) (any, error) {
}
result = append(result, map[string]any{"type": "input_text", "text": value})
case "image_url", "input_image":
imageURL, err := parseImageURL(part)
image, err := convertChatImagePart(part)
if err != nil {
return nil, err
}
result = append(result, map[string]any{"type": "input_image", "image_url": imageURL})
result = append(result, image)
default:
return nil, fmt.Errorf("不支持 content.type=%q", typeName)
}
@@ -178,19 +178,60 @@ func convertChatContent(raw json.RawMessage) (any, error) {
return result, nil
}
func parseImageURL(part map[string]json.RawMessage) (string, error) {
func convertChatToolOutput(raw json.RawMessage) (any, error) {
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
var parts []map[string]json.RawMessage
if json.Unmarshal(raw, &parts) != nil {
return contentAsText(raw)
}
hasImage := false
for _, part := range parts {
var typeName string
_ = json.Unmarshal(part["type"], &typeName)
if typeName == "image_url" || typeName == "input_image" {
hasImage = true
break
}
}
if !hasImage {
return contentAsText(raw)
}
return convertChatContent(raw)
}
func convertChatImagePart(part map[string]json.RawMessage) (map[string]any, error) {
imageURL, detail, err := parseImageURL(part)
if err != nil {
return nil, err
}
return map[string]any{"type": "input_image", "detail": detail, "image_url": imageURL}, nil
}
func parseImageURL(part map[string]json.RawMessage) (string, string, error) {
raw := firstJSON(part["image_url"], part["url"])
detail := "auto"
var directDetail string
if json.Unmarshal(part["detail"], &directDetail) == nil && strings.TrimSpace(directDetail) != "" {
detail = strings.TrimSpace(directDetail)
}
var value string
if json.Unmarshal(raw, &value) == nil && strings.TrimSpace(value) != "" {
return value, nil
return value, detail, nil
}
var nested struct {
URL string `json:"url"`
URL string `json:"url"`
Detail string `json:"detail"`
}
if json.Unmarshal(raw, &nested) == nil && strings.TrimSpace(nested.URL) != "" {
return nested.URL, nil
if strings.TrimSpace(nested.Detail) != "" {
detail = strings.TrimSpace(nested.Detail)
}
return nested.URL, detail, nil
}
return "", errors.New("image_url 缺少有效 url")
return "", "", errors.New("image_url 缺少有效 url")
}
func convertAssistantToolCalls(raw json.RawMessage) ([]any, error) {
@@ -43,12 +43,67 @@ func TestConvertChatRequestToResponses(t *testing.T) {
if content[1].(map[string]any)["image_url"] != "data:image/png;base64,AA==" {
t.Fatalf("image content = %#v", content)
}
if content[1].(map[string]any)["detail"] != "auto" {
t.Fatalf("image detail = %#v", content[1])
}
tools := payload["tools"].([]any)
if len(tools) != 2 || tools[0].(map[string]any)["name"] != "lookup" || tools[0].(map[string]any)["type"] != "function" || tools[1].(map[string]any)["type"] != "web_search" {
t.Fatalf("tools = %#v", tools)
}
}
func TestConvertChatToolImageResultToMultimodalFunctionOutput(t *testing.T) {
body := []byte(`{
"model":"public-chat",
"messages":[
{"role":"assistant","tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"call_1","content":[
{"type":"text","text":"Read image file"},
{"type":"image_url","image_url":{"url":"data:image/png;base64,AA==","detail":"high"}}
]}
]
}`)
converted, _, err := ConvertRequestWithOptions(body, "grok-4.5", OperationChat)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(converted, &payload); err != nil {
t.Fatal(err)
}
input := payload["input"].([]any)
output := input[1].(map[string]any)["output"].([]any)
if len(output) != 2 {
t.Fatalf("tool output = %#v", output)
}
textBlock := output[0].(map[string]any)
imageBlock := output[1].(map[string]any)
if textBlock["type"] != "input_text" || textBlock["text"] != "Read image file" ||
imageBlock["type"] != "input_image" || imageBlock["detail"] != "high" ||
imageBlock["image_url"] != "data:image/png;base64,AA==" {
t.Fatalf("tool output = %#v", output)
}
}
func TestConvertChatKeepsNonMultimodalToolJSONAsText(t *testing.T) {
body := []byte(`{
"model":"public-chat",
"messages":[{"role":"tool","tool_call_id":"call_1","content":[{"name":"value","value":1}]}]
}`)
converted, _, err := ConvertRequestWithOptions(body, "grok-4.5", OperationChat)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(converted, &payload); err != nil {
t.Fatal(err)
}
output := payload["input"].([]any)[0].(map[string]any)["output"]
if output != `[{"name":"value","value":1}]` {
t.Fatalf("tool output = %#v", output)
}
}
func TestConvertChatIgnoresSamplingFieldsWithoutResponsesEquivalent(t *testing.T) {
body := []byte(`{
"model":"public","messages":[{"role":"user","content":"hi"}],
@@ -314,7 +369,7 @@ func TestConvertAnthropicClaudeCodeRequestToResponses(t *testing.T) {
}
output := input[2].(map[string]any)["output"].([]any)
if len(output) != 4 || !strings.Contains(output[0].(map[string]any)["text"].(string), "failed") ||
!strings.Contains(output[2].(map[string]any)["text"].(string), `"Read"`) || output[3].(map[string]any)["type"] != "input_image" {
!strings.Contains(output[2].(map[string]any)["text"].(string), `"Read"`) || output[3].(map[string]any)["type"] != "input_image" || output[3].(map[string]any)["detail"] != "auto" {
t.Fatalf("tool result = %#v", output)
}
tools := payload["tools"].([]any)
@@ -503,7 +503,7 @@ func anthropicToolResult(raw json.RawMessage, declaredTools map[string]struct{})
if err != nil {
return nil, err
}
parts = append(parts, map[string]any{"type": "input_image", "image_url": imageURL})
parts = append(parts, map[string]any{"type": "input_image", "detail": "auto", "image_url": imageURL})
case "document":
document, err := anthropicDocument(block)
if err != nil {