Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog/unreleased/codearts-inline-images.md
Original file line number Diff line number Diff line change
@@ -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`。已下载的图片会短暂缓存,重放的历史轮次不会重复下载。
3 changes: 3 additions & 0 deletions internal/providers/codearts/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions internal/providers/codearts/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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,
}
Expand Down
246 changes: 246 additions & 0 deletions internal/providers/codearts/images.go
Original file line number Diff line number Diff line change
@@ -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),
}
}
Loading