mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
fix: preserve images in cross-protocol tool results
This commit is contained in:
1 parent
1e2702f6e0
commit
e98f386712
5 files changed
+454
-3
No files matched your search
@@ -0,0 +1,145 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
wire "opencode2api/internal/protocol"
|
||||
"opencode2api/internal/telemetry"
|
||||
)
|
||||
|
||||
// Exercise the real gateway handler and HTTP transport, not just converters.
|
||||
func TestToolImagesForwardedHTTP(t *testing.T) {
|
||||
for _, from := range []wire.Protocol{wire.Anthropic, wire.Responses} {
|
||||
for _, to := range []wire.Protocol{wire.Chat, wire.Responses, wire.Anthropic} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(string(from)+"-"+string(to)+map[bool]string{false: "-json", true: "-stream"}[stream], func(t *testing.T) {
|
||||
captured := make(chan map[string]any, 1)
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != wire.Path(to) {
|
||||
t.Errorf("upstream path %s", r.URL.Path)
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
captured <- body
|
||||
// Also prove a supplier rejection is surfaced, never retried without images.
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
io.WriteString(w, `{"error":{"message":"fixture rejects image","type":"invalid_request_error"}}`)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
path := filepath.Join(t.TempDir(), "config.json")
|
||||
cfgJSON := map[string]any{"server_keys": []string{"local-test"}, "go_keys": []string{"upstream-test"}, "upstream": map[string]string{"go": upstream.URL, "zen": upstream.URL}, "models": map[string]any{"protocols": map[string]string{"vision": string(to)}}}
|
||||
b, _ := json.Marshal(cfgJSON)
|
||||
if err := os.WriteFile(path, b, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g, err := New(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)), telemetry.NewMonitor())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g.catalog.Replace(nil, []string{"vision"})
|
||||
server := httptest.NewServer(g.Handler())
|
||||
defer server.Close()
|
||||
var input map[string]any
|
||||
json.Unmarshal([]byte(`{"model":"vision","messages":[{"role":"assistant","content":[{"type":"tool_use","id":"A","name":"read","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"A","content":[{"type":"text","text":"read result"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}]}`), &input)
|
||||
if from == wire.Responses {
|
||||
input, err = wire.ConvertRequest(wire.Anthropic, wire.Responses, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
input["stream"] = stream
|
||||
b, _ = json.Marshal(input)
|
||||
req, _ := http.NewRequest("POST", server.URL+wire.Path(from), bytes.NewReader(b))
|
||||
req.Header.Set("Authorization", "Bearer local-test")
|
||||
resp, err := server.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
response, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != 400 || !strings.Contains(string(response), "fixture rejects image") {
|
||||
t.Fatalf("status=%d body=%s", resp.StatusCode, response)
|
||||
}
|
||||
select {
|
||||
case body := <-captured:
|
||||
encoded, _ := json.Marshal(body)
|
||||
if bytes.Contains(encoded, []byte(`\"source\"`)) || bytes.Contains(encoded, []byte(`\"input_image\"`)) {
|
||||
t.Fatal("image stringified")
|
||||
}
|
||||
if strings.Count(string(encoded), "aW1hZ2U=") != 1 {
|
||||
t.Fatalf("image lost or duplicated: %s", encoded)
|
||||
}
|
||||
if body["stream"] != stream {
|
||||
t.Fatal("stream flag changed")
|
||||
}
|
||||
if to == wire.Chat {
|
||||
messages := body["messages"].([]any)
|
||||
tool := messages[1].(map[string]any)
|
||||
if strings.Contains(tool["content"].(string), "aW1hZ2U=") {
|
||||
t.Fatal("base64 in tool text")
|
||||
}
|
||||
}
|
||||
default:
|
||||
t.Fatal("no upstream request")
|
||||
}
|
||||
if from != to {
|
||||
var removeSources func(any)
|
||||
removeSources = func(v any) {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
if x["type"] == "image" {
|
||||
delete(x, "source")
|
||||
}
|
||||
if x["type"] == "input_image" {
|
||||
delete(x, "image_url")
|
||||
}
|
||||
for _, child := range x {
|
||||
removeSources(child)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range x {
|
||||
removeSources(child)
|
||||
}
|
||||
}
|
||||
}
|
||||
removeSources(input)
|
||||
b, _ = json.Marshal(input)
|
||||
req, _ = http.NewRequest("POST", server.URL+wire.Path(from), bytes.NewReader(b))
|
||||
req.Header.Set("Authorization", "Bearer local-test")
|
||||
bad, err := server.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
io.Copy(io.Discard, bad.Body)
|
||||
bad.Body.Close()
|
||||
if bad.StatusCode != 400 {
|
||||
t.Fatalf("invalid image status: %d", bad.StatusCode)
|
||||
}
|
||||
select {
|
||||
case <-captured:
|
||||
t.Fatal("invalid image reached upstream")
|
||||
default:
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,7 +282,11 @@ func encodeAnthropicBlocks(blocks []bridgeBlock) []any {
|
||||
}
|
||||
parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input})
|
||||
case "tool_result":
|
||||
parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": block.Result, "is_error": block.IsError})
|
||||
content := block.Result
|
||||
if blocks, ok := content.([]bridgeBlock); ok {
|
||||
content = encodeAnthropicBlocks(blocks)
|
||||
}
|
||||
parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": content, "is_error": block.IsError})
|
||||
case "reasoning":
|
||||
if block.Encrypted != "" {
|
||||
parts = append(parts, map[string]any{"type": "redacted_thinking", "data": block.Encrypted})
|
||||
|
||||
@@ -564,6 +564,22 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
|
||||
default:
|
||||
return request, fmt.Errorf("unsupported input protocol %q", protocol)
|
||||
}
|
||||
for i := range request.Messages {
|
||||
for j := range request.Messages[i].Blocks {
|
||||
block := &request.Messages[i].Blocks[j]
|
||||
if block.Kind != "tool_result" || protocol == Chat {
|
||||
continue
|
||||
}
|
||||
result, err := decodeToolImages(protocol, block.Result)
|
||||
if err != nil {
|
||||
return request, fmt.Errorf("messages[%d].tool_result[%d]: %w", i, j, err)
|
||||
}
|
||||
if _, images := result.([]bridgeBlock); images && block.CallID == "" {
|
||||
return request, fmt.Errorf("messages[%d]: tool image result requires a call ID", i)
|
||||
}
|
||||
block.Result = result
|
||||
}
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
|
||||
@@ -782,14 +798,22 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
|
||||
}
|
||||
}
|
||||
if len(pending) == 0 && len(pendingOrder) > 0 {
|
||||
var attachments []map[string]any
|
||||
for _, id := range pendingOrder {
|
||||
result := pendingResults[id]
|
||||
text, images := chatToolImages(result)
|
||||
if len(images) > 0 {
|
||||
attachments = append(attachments, map[string]any{"role": "user", "content": encodeChatBlocks(images)})
|
||||
}
|
||||
messages = append(messages, map[string]any{
|
||||
"role": "tool",
|
||||
"tool_call_id": id,
|
||||
"content": bridgeToolResultContent(result.Result),
|
||||
"content": text,
|
||||
})
|
||||
}
|
||||
for _, attachment := range attachments {
|
||||
messages = append(messages, attachment)
|
||||
}
|
||||
flushDeferred()
|
||||
pendingOrder = nil
|
||||
clear(pendingResults)
|
||||
@@ -981,7 +1005,7 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any {
|
||||
items = append(items, map[string]any{
|
||||
"type": "function_call_output",
|
||||
"call_id": block.CallID,
|
||||
"output": bridgeToolResultContent(block.Result),
|
||||
"output": responsesToolContent(block.Result),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"opencode2api/internal/jsonutil"
|
||||
)
|
||||
|
||||
// Only image-bearing tool results enter this path. Keep all legacy text and
|
||||
// opaque results unchanged, and reuse bridgeBlock rather than a second model.
|
||||
func decodeToolImages(from Protocol, value any) (any, error) {
|
||||
parts, ok := value.([]any)
|
||||
if !ok {
|
||||
return value, nil
|
||||
}
|
||||
imageType, textType := "input_image", "input_text"
|
||||
if from == Anthropic {
|
||||
imageType, textType = "image", "text"
|
||||
}
|
||||
hasImage := false
|
||||
for _, raw := range parts {
|
||||
part, _ := raw.(map[string]any)
|
||||
hasImage = hasImage || jsonutil.StringAt(part, "type") == imageType
|
||||
}
|
||||
if !hasImage {
|
||||
return value, nil
|
||||
}
|
||||
for i, raw := range parts {
|
||||
part, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("content[%d] must be an object", i)
|
||||
}
|
||||
switch jsonutil.StringAt(part, "type") {
|
||||
case textType:
|
||||
if _, ok := part["text"].(string); !ok {
|
||||
return nil, fmt.Errorf("content[%d] requires text", i)
|
||||
}
|
||||
case imageType:
|
||||
if from == Anthropic {
|
||||
source := jsonutil.MapAt(part, "source")
|
||||
valid := false
|
||||
switch jsonutil.StringAt(source, "type") {
|
||||
case "url":
|
||||
valid = jsonutil.StringAt(source, "url") != "" && source["data"] == nil && source["file_id"] == nil
|
||||
case "base64":
|
||||
valid = jsonutil.StringAt(source, "data") != "" && strings.HasPrefix(jsonutil.StringAt(source, "media_type"), "image/") && source["url"] == nil && source["file_id"] == nil
|
||||
}
|
||||
if !valid {
|
||||
return nil, fmt.Errorf("content[%d] has an unsupported or conflicting image source", i)
|
||||
}
|
||||
} else if jsonutil.StringAt(part, "image_url") == "" || part["file_id"] != nil {
|
||||
return nil, fmt.Errorf("content[%d] requires an image URL without a file reference", i)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("content[%d] contains an unsupported block alongside tool images", i)
|
||||
}
|
||||
}
|
||||
if from == Anthropic {
|
||||
return decodeAnthropicBlocksChecked(value)
|
||||
}
|
||||
blocks, err := decodeOpenAIBlocksChecked(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range blocks {
|
||||
block := &blocks[i]
|
||||
if block.Kind != "image" || !strings.HasPrefix(block.URL, "data:") {
|
||||
continue
|
||||
}
|
||||
header, data, ok := strings.Cut(strings.TrimPrefix(block.URL, "data:"), ",")
|
||||
media, base64 := strings.CutSuffix(header, ";base64")
|
||||
if !ok || !base64 || !strings.HasPrefix(media, "image/") || data == "" {
|
||||
return nil, fmt.Errorf("content[%d] has an invalid image data URI", i)
|
||||
}
|
||||
block.URL, block.MediaType, block.Data = "", media, data
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
func chatToolImages(result bridgeBlock) (string, []bridgeBlock) {
|
||||
parts, ok := result.Result.([]bridgeBlock)
|
||||
if !ok {
|
||||
return bridgeToolResultContent(result.Result), nil
|
||||
}
|
||||
var text strings.Builder
|
||||
var images []bridgeBlock
|
||||
n := 0
|
||||
for _, part := range parts {
|
||||
if part.Kind == "text" {
|
||||
text.WriteString(part.Text)
|
||||
continue
|
||||
}
|
||||
n++
|
||||
marker := fmt.Sprintf("[tool_image call_id=%s index=%d]", bridgeArgumentsJSON(bridgeBlock{Arguments: result.CallID}), n)
|
||||
text.WriteString("\n" + marker + "\n")
|
||||
images = append(images, bridgeBlock{Kind: "text", Text: marker}, part)
|
||||
}
|
||||
return text.String(), images
|
||||
}
|
||||
|
||||
func responsesToolContent(value any) any {
|
||||
parts, ok := value.([]bridgeBlock)
|
||||
if !ok {
|
||||
return bridgeToolResultContent(value)
|
||||
}
|
||||
content := make([]any, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if part.Kind == "text" {
|
||||
content = append(content, map[string]any{"type": "input_text", "text": part.Text})
|
||||
} else {
|
||||
url := part.URL
|
||||
if url == "" {
|
||||
url = "data:" + part.MediaType + ";base64," + part.Data
|
||||
}
|
||||
content = append(content, map[string]any{"type": "input_image", "image_url": url})
|
||||
}
|
||||
}
|
||||
return content
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func toolImageRequest(t *testing.T) map[string]any {
|
||||
t.Helper()
|
||||
var request map[string]any
|
||||
err := json.Unmarshal([]byte(`{"model":"vision","messages":[
|
||||
{"role":"assistant","content":[{"type":"tool_use","id":"A","name":"read","input":{}},{"type":"tool_use","id":"B","name":"read","input":{}}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"B","content":[{"type":"image","source":{"type":"url","url":"https://example.test/b.png"}}]}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"A","content":[{"type":"text","text":"before"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}},{"type":"text","text":"after"},{"type":"image","source":{"type":"url","url":"https://example.test/a2.png"}}]},{"type":"text","text":"compare"},{"type":"image","source":{"type":"url","url":"https://example.test/user.png"}}]}]}`), &request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
func TestToolImagesChatOrderAndPurity(t *testing.T) {
|
||||
input := toolImageRequest(t)
|
||||
before, _ := json.Marshal(input)
|
||||
for _, from := range []Protocol{Anthropic, Responses} {
|
||||
source := input
|
||||
if from == Responses {
|
||||
var err error
|
||||
source, err = ConvertRequest(Anthropic, Responses, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for run := 0; run < 2; run++ {
|
||||
out, err := ConvertRequest(from, Chat, source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
messages := out["messages"].([]any)
|
||||
if len(messages) != 6 {
|
||||
t.Fatalf("messages: %#v", messages)
|
||||
}
|
||||
for i, id := range []string{"A", "B"} {
|
||||
tool := messages[i+1].(map[string]any)
|
||||
if tool["role"] != "tool" || tool["tool_call_id"] != id {
|
||||
t.Fatalf("tool order: %#v", tool)
|
||||
}
|
||||
text := tool["content"].(string)
|
||||
if strings.Contains(text, "aW1hZ2U=") || !strings.Contains(text, `call_id="`+id+`"`) {
|
||||
t.Fatalf("tool content: %s", text)
|
||||
}
|
||||
}
|
||||
a := messages[3].(map[string]any)["content"].([]any)
|
||||
if len(a) != 4 || a[1].(map[string]any)["image_url"].(map[string]any)["url"] != "data:image/png;base64,aW1hZ2U=" {
|
||||
t.Fatalf("attachments: %#v", a)
|
||||
}
|
||||
if !strings.Contains(a[2].(map[string]any)["text"].(string), "index=2") {
|
||||
t.Fatal("image index lost")
|
||||
}
|
||||
last, _ := json.Marshal(messages[5])
|
||||
if !strings.Contains(string(last), "user.png") {
|
||||
t.Fatal("user image lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
after, _ := json.Marshal(input)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("input mutated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolImagesNativeAndPassThrough(t *testing.T) {
|
||||
input := toolImageRequest(t)
|
||||
r, err := ConvertRequest(Anthropic, Responses, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items := r["input"].([]any)
|
||||
for _, raw := range items {
|
||||
item := raw.(map[string]any)
|
||||
if item["type"] == "function_call_output" {
|
||||
if _, ok := item["output"].([]any); !ok {
|
||||
t.Fatal("tool image stringified")
|
||||
}
|
||||
}
|
||||
}
|
||||
a, err := ConvertRequest(Responses, Anthropic, r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encoded, _ := json.Marshal(a)
|
||||
if strings.Contains(string(encoded), "input_image") || !strings.Contains(string(encoded), `"type":"base64"`) {
|
||||
t.Fatalf("native image conversion: %s", encoded)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
p Protocol
|
||||
input map[string]any
|
||||
}{{Anthropic, input}, {Responses, r}, {Chat, map[string]any{"messages": []any{map[string]any{"role": "tool", "content": "unchanged"}}}}} {
|
||||
out, err := ConvertRequest(tc.p, tc.p, tc.input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b1, _ := json.Marshal(out)
|
||||
b2, _ := json.Marshal(tc.input)
|
||||
if string(b1) != string(b2) {
|
||||
t.Fatal("passthrough changed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolImagesRejectMalformedAndPreserveText(t *testing.T) {
|
||||
for _, value := range []any{nil, "", "plain", []any{map[string]any{"type": "text", "text": "a"}, map[string]any{"type": "text", "text": "b"}}} {
|
||||
out, err := decodeToolImages(Anthropic, value)
|
||||
if err != nil || !reflect.DeepEqual(out, value) {
|
||||
t.Fatal("legacy result changed")
|
||||
}
|
||||
}
|
||||
for _, tail := range []any{nil, map[string]any{"type": "document"}, map[string]any{"type": "tool_result"}, map[string]any{"type": "text"}, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": "x", "data": "secret"}}} {
|
||||
value := []any{map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": "https://example.test/a"}}, tail}
|
||||
if _, err := decodeToolImages(Anthropic, value); err == nil {
|
||||
t.Fatalf("accepted malformed block: %#v", tail)
|
||||
}
|
||||
}
|
||||
for _, image := range []map[string]any{{"type": "input_image"}, {"type": "input_image", "file_id": "secret"}, {"type": "input_image", "image_url": "data:bad"}} {
|
||||
if _, err := decodeToolImages(Responses, []any{image}); err == nil {
|
||||
t.Fatal("accepted unsupported image")
|
||||
}
|
||||
}
|
||||
input := toolImageRequest(t)
|
||||
messages := input["messages"].([]any)
|
||||
input["messages"] = messages[:2]
|
||||
if _, err := ConvertRequest(Anthropic, Chat, input); err == nil {
|
||||
t.Fatal("accepted missing tool result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolImagesMultipleRounds(t *testing.T) {
|
||||
input := toolImageRequest(t)
|
||||
messages := input["messages"].([]any)
|
||||
// Reusing call IDs in a later, completed round must not retain attachments.
|
||||
input["messages"] = append(messages, messages...)
|
||||
out, err := ConvertRequest(Anthropic, Chat, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encoded, _ := json.Marshal(out)
|
||||
if strings.Count(string(encoded), "aW1hZ2U=") != 2 || len(out["messages"].([]any)) != 12 {
|
||||
t.Fatal("attachments leaked between rounds")
|
||||
}
|
||||
|
||||
input = toolImageRequest(t)
|
||||
messages = input["messages"].([]any)
|
||||
input["messages"] = append(messages[:2], messages[1], messages[2])
|
||||
if _, err := ConvertRequest(Anthropic, Chat, input); err == nil {
|
||||
t.Fatal("duplicate result accepted")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user