diff --git a/changelog/unreleased/codearts-inline-images.md b/changelog/unreleased/codearts-inline-images.md new file mode 100644 index 00000000..c0455ab3 --- /dev/null +++ b/changelog/unreleased/codearts-inline-images.md @@ -0,0 +1,7 @@ +### English + +- CodeArts vision requests now inline remote image URLs as base64 data URLs before the call, so clients that send signed object-storage links (for example a Qoder or WorkBuddy custom endpoint) no longer fail with `InferHub.ModelArts.81001.400 unsupported image url`. Downloaded images are cached briefly so replayed turns are not re-fetched. + +### 中文 + +- 码道视觉请求现在会在调用前把远程图片 URL 内联为 base64 data URL,发送签名对象存储链接的客户端(如 Qoder / WorkBuddy 自定义端点)不再报 `InferHub.ModelArts.81001.400 unsupported image url`。已下载的图片会短暂缓存,重放的历史轮次不会重复下载。 diff --git a/internal/providers/codearts/chat.go b/internal/providers/codearts/chat.go index ecc69928..4f9187a4 100644 --- a/internal/providers/codearts/chat.go +++ b/internal/providers/codearts/chat.go @@ -120,6 +120,9 @@ func (c *Client) doChat(ctx context.Context, accountID string, req translate.Cha } } model = c.canonicalModel(accountID, model) + if err := c.inlineMessageImages(ctx, accountID, req.Messages); err != nil { + return nil, "", err + } level, caps := c.resolveLevel(ctx, accountID, model, requestedLevel(req)) body, err := buildChatBody(req, model, level, caps.Images, c.isBenefitModel(accountID, model)) if err != nil { diff --git a/internal/providers/codearts/client.go b/internal/providers/codearts/client.go index d627f101..114042ac 100644 --- a/internal/providers/codearts/client.go +++ b/internal/providers/codearts/client.go @@ -55,6 +55,8 @@ type Client struct { catalogs map[string]catalogCache locks map[string]*sync.Mutex logins map[string]*loginState + // images caches remote attachments already inlined to data: URLs. + images *imageCache // availability is a learned per-account model verdict from real traffic. availability map[string]modelAvailability } @@ -80,6 +82,7 @@ func NewClient(store Store) *Client { catalogs: map[string]catalogCache{}, locks: map[string]*sync.Mutex{}, logins: map[string]*loginState{}, + images: newImageCache(), availability: map[string]modelAvailability{}, nowFn: time.Now, } diff --git a/internal/providers/codearts/images.go b/internal/providers/codearts/images.go new file mode 100644 index 00000000..89ae3102 --- /dev/null +++ b/internal/providers/codearts/images.go @@ -0,0 +1,246 @@ +package codearts + +import ( + "context" + "encoding/base64" + "fmt" + "io" + "mime" + "net/http" + "net/url" + "path" + "strings" + "sync" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +// The inference endpoint only accepts inline data: URLs for image parts. +// Remote http(s) references fail with InferHub.ModelArts.81001.400 +// "unsupported image url", and hosted-agent clients (Qoder/WorkBuddy custom +// endpoints) legitimately send signed object-storage links for their +// attachments. The adapter therefore downloads each remote image once and +// rewrites the part to base64 before the request is mapped. +const ( + imageDownloadTimeout = 45 * time.Second + imageMaxBytes = 20 << 20 + imageCacheTTL = 10 * time.Minute + imageCacheMaxEntries = 16 + imageCacheMaxBytes = 64 << 20 +) + +type imageCacheEntry struct { + dataURL string + bytes int + expires time.Time +} + +// imageCache remembers inlined images briefly so replayed conversation turns +// do not re-download the same attachment on every request. +type imageCache struct { + mu sync.Mutex + order []string + entries map[string]imageCacheEntry +} + +func newImageCache() *imageCache { + return &imageCache{entries: map[string]imageCacheEntry{}} +} + +func (c *imageCache) get(key string, now time.Time) (string, bool) { + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.entries[key] + if !ok || now.After(entry.expires) { + return "", false + } + return entry.dataURL, true +} + +func (c *imageCache) put(key, dataURL string, now time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + if c.entries == nil { + c.entries = map[string]imageCacheEntry{} + } + if _, exists := c.entries[key]; !exists { + c.order = append(c.order, key) + } + c.entries[key] = imageCacheEntry{dataURL: dataURL, bytes: len(dataURL), expires: now.Add(imageCacheTTL)} + total := 0 + for _, entry := range c.entries { + total += entry.bytes + } + for len(c.order) > 0 && (len(c.order) > imageCacheMaxEntries || total > imageCacheMaxBytes) { + oldest := c.order[0] + c.order = c.order[1:] + if entry, ok := c.entries[oldest]; ok { + total -= entry.bytes + delete(c.entries, oldest) + } + } +} + +// inlineMessageImages rewrites every remote image URL in the request into an +// inline data: URL. Parts already carrying data: URLs are left untouched, and +// messages without images cost one type assertion each. +func (c *Client) inlineMessageImages(ctx context.Context, accountID string, messages []translate.ChatMessage) error { + if !messagesHaveRemoteImage(messages) { + return nil + } + client, err := c.httpClient(ctx, accountID) + if err != nil { + return err + } + var firstErr error + for index := range messages { + items, ok := messages[index].Content.([]any) + if !ok { + continue + } + for _, item := range items { + block, ok := item.(map[string]any) + if !ok { + continue + } + kind := strings.ToLower(strings.TrimSpace(stringValue(block["type"]))) + if kind != "image_url" && kind != "input_image" && kind != "image" { + continue + } + url := imageURLFromPart(block) + if !isRemoteImageURL(url) { + continue + } + dataURL, err := inlineImageURL(ctx, client, c.images, url) + if err != nil { + if firstErr == nil { + firstErr = err + } + continue + } + rewriteImagePartURL(block, dataURL) + } + } + return firstErr +} + +func messagesHaveRemoteImage(messages []translate.ChatMessage) bool { + for _, message := range messages { + items, ok := message.Content.([]any) + if !ok { + continue + } + for _, item := range items { + block, ok := item.(map[string]any) + if !ok { + continue + } + kind := strings.ToLower(strings.TrimSpace(stringValue(block["type"]))) + if kind != "image_url" && kind != "input_image" && kind != "image" { + continue + } + if isRemoteImageURL(imageURLFromPart(block)) { + return true + } + } + } + return false +} + +func isRemoteImageURL(rawURL string) bool { + return strings.HasPrefix(rawURL, "http://") || strings.HasPrefix(rawURL, "https://") +} + +func rewriteImagePartURL(block map[string]any, dataURL string) { + switch value := block["image_url"].(type) { + case map[string]any: + value["url"] = dataURL + case string: + block["image_url"] = dataURL + default: + block["image_url"] = map[string]any{"url": dataURL} + } +} + +// inlineImageURL returns a data: URL for the given image reference. data: URLs +// pass through untouched; http(s) URLs are downloaded through the provided +// client and base64-encoded with a sniffed or declared MIME type. +func inlineImageURL(ctx context.Context, client *http.Client, cache *imageCache, rawURL string) (string, error) { + rawURL = strings.TrimSpace(rawURL) + if rawURL == "" || strings.HasPrefix(rawURL, "data:") || !isRemoteImageURL(rawURL) { + return rawURL, nil + } + now := time.Now() + if cache != nil { + if dataURL, ok := cache.get(rawURL, now); ok { + return dataURL, nil + } + } + if client == nil { + return "", &providers.Error{ + Kind: accounts.KindInvalidRequest, + Status: http.StatusBadRequest, + Message: "codearts image part is a remote URL but no HTTP client is available to inline it", + } + } + downloadCtx, cancel := context.WithTimeout(ctx, imageDownloadTimeout) + defer cancel() + req, err := http.NewRequestWithContext(downloadCtx, http.MethodGet, rawURL, nil) + if err != nil { + return "", wrapImageError(rawURL, err) + } + resp, err := client.Do(req) + if err != nil { + return "", wrapImageError(rawURL, err) + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + return "", wrapImageError(rawURL, fmt.Errorf("download returned %s", resp.Status)) + } + payload, err := io.ReadAll(io.LimitReader(resp.Body, imageMaxBytes+1)) + if err != nil { + return "", wrapImageError(rawURL, err) + } + if len(payload) > imageMaxBytes { + return "", wrapImageError(rawURL, fmt.Errorf("image exceeds %d bytes", imageMaxBytes)) + } + dataURL := "data:" + imageMimeType(resp, req.URL.Path, payload) + ";base64," + base64.StdEncoding.EncodeToString(payload) + if cache != nil { + cache.put(rawURL, dataURL, now) + } + return dataURL, nil +} + +// imageMimeType prefers the served Content-Type, then content sniffing, then +// the URL extension, so re-encoded or mislabeled object storage still yields a +// usable type instead of defaulting everything to png. +func imageMimeType(resp *http.Response, urlPath string, payload []byte) string { + if mimeType := strings.TrimSpace(resp.Header.Get("Content-Type")); strings.HasPrefix(mimeType, "image/") { + if semicolon := strings.Index(mimeType, ";"); semicolon > 0 { + mimeType = mimeType[:semicolon] + } + return strings.TrimSpace(mimeType) + } + if detected := http.DetectContentType(payload); strings.HasPrefix(detected, "image/") { + return detected + } + if guessed := mime.TypeByExtension(strings.ToLower(path.Ext(urlPath))); guessed != "" { + return guessed + } + return "image/png" +} + +func wrapImageError(rawURL string, err error) error { + host := rawURL + if parsed, parseErr := url.Parse(rawURL); parseErr == nil && parsed.Host != "" { + host = parsed.Host + } + return &providers.Error{ + Kind: accounts.KindInvalidRequest, + Status: http.StatusBadRequest, + Message: fmt.Sprintf("codearts upstream only accepts inline images and the remote image could not be fetched (%s): %v", host, err), + } +} diff --git a/internal/providers/codearts/images_test.go b/internal/providers/codearts/images_test.go new file mode 100644 index 00000000..0c2d2beb --- /dev/null +++ b/internal/providers/codearts/images_test.go @@ -0,0 +1,143 @@ +package codearts + +import ( + "context" + "encoding/base64" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func testPNG() []byte { + // 1x1 white pixel PNG. + raw, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/x8AAwMB/6Xv0AAAAABJRU5ErkJggg==") + return raw +} + +func TestInlineImageURLPassesThroughDataAndPlainValues(t *testing.T) { + client := NewClient(&memoryStore{payload: mustTestCredential(t)}) + for _, value := range []string{"", "data:image/png;base64,AAAA", "not-a-url"} { + got, err := inlineImageURL(context.Background(), client.http, client.images, value) + if err != nil { + t.Fatalf("inline(%q) error: %v", value, err) + } + if got != value { + t.Fatalf("inline(%q) = %q", value, got) + } + } +} + +func TestInlineImageURLDownloadsAndInlines(t *testing.T) { + png := testPNG() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(png) + })) + defer server.Close() + + client := NewClient(&memoryStore{payload: mustTestCredential(t)}) + got, err := inlineImageURL(context.Background(), client.http, client.images, server.URL+"/a.png") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(got, "data:image/png;base64,") { + t.Fatalf("data URL = %q", got) + } + if decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(got, "data:image/png;base64,")); err != nil || string(decoded) != string(png) { + t.Fatalf("decoded payload mismatch (err=%v)", err) + } +} + +func TestInlineImageURLSniffsMimeWhenHeaderMissing(t *testing.T) { + png := testPNG() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write(png) // no Content-Type header + })) + defer server.Close() + + client := NewClient(&memoryStore{payload: mustTestCredential(t)}) + got, err := inlineImageURL(context.Background(), client.http, client.images, server.URL+"/a.bin") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(got, "data:image/png;base64,") { + t.Fatalf("data URL = %q", got) + } +} + +func TestInlineImageURLUsesCacheOnSecondFetch(t *testing.T) { + var hits int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(testPNG()) + })) + defer server.Close() + + client := NewClient(&memoryStore{payload: mustTestCredential(t)}) + imageURL := server.URL + "/only.png" + first, err := inlineImageURL(context.Background(), client.http, client.images, imageURL) + if err != nil { + t.Fatal(err) + } + second, err := inlineImageURL(context.Background(), client.http, client.images, imageURL) + if err != nil { + t.Fatal(err) + } + if first != second { + t.Fatal("second fetch did not reuse the cached data URL") + } + if atomic.LoadInt32(&hits) != 1 { + t.Fatalf("origin hits = %d, want 1", hits) + } +} + +func TestInlineImageURLFailsCleanlyOnHTTPError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NotFound(w, r) + })) + defer server.Close() + + client := NewClient(&memoryStore{payload: mustTestCredential(t)}) + _, err := inlineImageURL(context.Background(), client.http, client.images, server.URL+"/missing.png") + if err == nil { + t.Fatal("expected an error for a 404 image") + } + if !strings.Contains(err.Error(), "404") { + t.Fatalf("error = %v", err) + } +} + +func TestInlineMessageImagesRewritesPartsInPlace(t *testing.T) { + png := testPNG() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(png) + })) + defer server.Close() + + client := NewClient(&memoryStore{payload: mustTestCredential(t)}) + messages := []translate.ChatMessage{{ + Role: "user", + Content: []any{ + map[string]any{"type": "text", "text": "what is this?"}, + map[string]any{"type": "image_url", "image_url": map[string]any{"url": server.URL + "/shot.png"}}, + map[string]any{"type": "image_url", "image_url": "data:image/png;base64,AAAA"}, + }, + }} + if err := client.inlineMessageImages(context.Background(), "acct-1", messages); err != nil { + t.Fatal(err) + } + parts := messages[0].Content.([]any) + rewritten := parts[1].(map[string]any)["image_url"].(map[string]any)["url"].(string) + if !strings.HasPrefix(rewritten, "data:image/png;base64,") { + t.Fatalf("rewritten url = %q", rewritten) + } + if got := parts[2].(map[string]any)["image_url"]; got != "data:image/png;base64,AAAA" { + t.Fatalf("existing data URL was modified: %v", got) + } +}