diff --git a/internal/http/provider_models_catalog.go b/internal/http/provider_models_catalog.go index 750acfe930..9ad89a3138 100644 --- a/internal/http/provider_models_catalog.go +++ b/internal/http/provider_models_catalog.go @@ -34,6 +34,8 @@ func minimaxModels() []ModelInfo { }}, {ID: "MiniMax-M3", Name: "MiniMax M3"}, // Image generation + {ID: "MiniMax-H3-Image", Name: "MiniMax H3 Image"}, + {ID: "MiniMax-H3-Image-Highspeed", Name: "MiniMax H3 Image Highspeed"}, {ID: "image-01", Name: "Image 01"}, // Video generation {ID: "MiniMax-Hailuo-2.3", Name: "Hailuo Video 2.3"}, diff --git a/internal/http/provider_models_test.go b/internal/http/provider_models_test.go index ae233b5fe3..42a3dc372d 100644 --- a/internal/http/provider_models_test.go +++ b/internal/http/provider_models_test.go @@ -214,11 +214,12 @@ func TestProvidersHandlerListProviderModelsMiniMaxPrefersFlash(t *testing.T) { result := providerModelsRequest(t, mux, provider.ID, token) wantIDs := []string{ "MiniMax-M3.1-Flash", "MiniMax-M3", + "MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed", "image-01", "MiniMax-Hailuo-2.3", "MiniMax-Hailuo-2", "T2V-01-Director", "music-2.5+", "music-2.5", "speech-02-hd", "speech-02-turbo", } if len(result.Models) != len(wantIDs) { - t.Fatalf("models = %#v, want current text models and unchanged media", result.Models) + t.Fatalf("models = %#v, want current text and media models", result.Models) } for i, want := range wantIDs { if result.Models[i].ID != want { diff --git a/internal/tools/create_image.go b/internal/tools/create_image.go index e3b4e6c093..4171082619 100644 --- a/internal/tools/create_image.go +++ b/internal/tools/create_image.go @@ -422,6 +422,12 @@ func (t *CreateImageTool) callProvider(ctx context.Context, cp credentialProvide case "openrouter": return t.callImageGenAPI(ctx, cp.APIKey(), cp.APIBase(), model, prompt, aspectRatio, params) case "minimax": + if isMinimaxH3Image(model) { + if len(refImgs) > 0 { + return nil, nil, fmt.Errorf("%s requires a text-only prompt", model) + } + return callMinimaxH3Image(ctx, cp.APIKey(), cp.APIBase(), model, prompt, params) + } return callMinimaxImageGen(ctx, cp.APIKey(), cp.APIBase(), model, prompt, params) case "dashscope": return callDashScopeImageGen(ctx, cp.APIKey(), cp.APIBase(), model, prompt, params) diff --git a/internal/tools/create_image_minimax_h3.go b/internal/tools/create_image_minimax_h3.go new file mode 100644 index 0000000000..7452b97d5e --- /dev/null +++ b/internal/tools/create_image_minimax_h3.go @@ -0,0 +1,113 @@ +package tools + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + + "github.com/nextlevelbuilder/goclaw/internal/providers" +) + +var errMinimaxH3Submitted = errors.New("MiniMax H3 generation submitted") + +func isMinimaxH3Image(model string) bool { + return model == "MiniMax-H3-Image" || model == "MiniMax-H3-Image-Highspeed" +} + +func minimaxH3Endpoint(apiBase string) string { + base := strings.TrimRight(apiBase, "/") + if base == "https://api.minimaxi.com/v1" { + base = "https://api.minimax.cn/v1" + } + return base + "/images/generations" +} + +func callMinimaxH3Image(ctx context.Context, key, apiBase, model, prompt string, params map[string]any) ([]byte, *providers.Usage, error) { + body, err := json.Marshal(map[string]string{ + "model": model, "prompt": prompt, "aspect_ratio": minimaxImageAspectRatio(params), + "response_format": "b64_json", "output_format": "png", + }) + if err != nil { + return nil, nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, minimaxH3Endpoint(apiBase), bytes.NewReader(body)) + if err != nil { + return nil, nil, err + } + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("Content-Type", "application/json") + // The POST is billable and non-idempotent, including on 307/308 redirects. + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + resp, err := client.Do(req) + if err != nil { + return nil, nil, fmt.Errorf("%w: %w", errMinimaxH3Submitted, err) + } + defer resp.Body.Close() + img, usage, err := readMinimaxH3Image(resp) + if err != nil { + return nil, nil, fmt.Errorf("%w: %w", errMinimaxH3Submitted, err) + } + return img, usage, nil +} + +func readMinimaxH3Image(resp *http.Response) ([]byte, *providers.Usage, error) { + if resp.StatusCode != http.StatusOK { + var failure struct { + Error struct { + Message string `json:"message"` + } `json:"error"` + } + if json.NewDecoder(io.LimitReader(resp.Body, 32<<10)).Decode(&failure) == nil && failure.Error.Message != "" { + return nil, nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, failure.Error.Message) + } + return nil, nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + var result struct { + Data []struct { + Base64 string `json:"b64_json"` + Error *struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } `json:"data"` + Usage *struct { + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + TotalTokens int `json:"total_tokens"` + GeneratedImages int `json:"generated_images"` + } `json:"usage"` + } + // create_image returns one PNG; the request uses the API default of n=1. + if err := json.NewDecoder(io.LimitReader(resp.Body, maxMediaDownloadBytes)).Decode(&result); err != nil { + return nil, nil, fmt.Errorf("decode response: %w", err) + } + if len(result.Data) != 1 { + return nil, nil, fmt.Errorf("expected one image, got %d", len(result.Data)) + } + item := result.Data[0] + if item.Error != nil { + return nil, nil, fmt.Errorf("%s: %s", item.Error.Code, item.Error.Message) + } + if item.Base64 == "" { + return nil, nil, fmt.Errorf("empty image data") + } + img, err := base64.StdEncoding.DecodeString(item.Base64) + if err != nil { + return nil, nil, fmt.Errorf("decode image: %w", err) + } + var usage *providers.Usage + if u := result.Usage; u != nil { + usage = &providers.Usage{ + PromptTokens: u.InputTokens, CompletionTokens: u.OutputTokens, + TotalTokens: u.TotalTokens, ImageCount: u.GeneratedImages, + } + } + return img, usage, nil +} diff --git a/internal/tools/create_image_minimax_h3_test.go b/internal/tools/create_image_minimax_h3_test.go new file mode 100644 index 0000000000..19249f6de5 --- /dev/null +++ b/internal/tools/create_image_minimax_h3_test.go @@ -0,0 +1,137 @@ +package tools + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "image" + "image/png" + "maps" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/nextlevelbuilder/goclaw/internal/providers" +) + +func TestCreateImageMinimaxH3(t *testing.T) { + var img bytes.Buffer + if err := png.Encode(&img, image.NewGray(image.Rect(0, 0, 1, 1))); err != nil { + t.Fatal(err) + } + success := fmt.Sprintf(`{"data":[{"b64_json":"%s"}],"usage":{"input_tokens":2,"output_tokens":3,"total_tokens":5,"generated_images":1}}`, base64.StdEncoding.EncodeToString(img.Bytes())) + for _, tc := range []struct { + name, model string + status int + body, wantError string + }{ + {"standard", "MiniMax-H3-Image", 200, success, ""}, + {"highspeed", "MiniMax-H3-Image-Highspeed", 200, success, ""}, + {"item error", "MiniMax-H3-Image", 200, `{"data":[{"error":{"code":"1027","message":"image withheld"}}]}`, "1027: image withheld"}, + {"service error", "MiniMax-H3-Image", 422, `{"error":{"type":"unprocessable_entity_error","http_code":"422","message":"invalid prompt"}}`, "invalid prompt"}, + {"redirect", "MiniMax-H3-Image", 307, "", "HTTP 307"}, + {"empty data", "MiniMax-H3-Image", 200, `{"data":[]}`, "expected one image"}, + {"malformed image", "MiniMax-H3-Image", 200, `{"data":[{"b64_json":"!"}]}`, "decode image"}, + } { + t.Run(tc.name, func(t *testing.T) { + var posts atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + posts.Add(1) + if r.Method != http.MethodPost || r.URL.Path != "/v1/images/generations" || r.Header.Get("Authorization") != "Bearer test-key" { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + } + var body map[string]string + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + want := map[string]string{ + "model": tc.model, "prompt": "a tree", "aspect_ratio": "16:9", + "response_format": "b64_json", "output_format": "png", + } + if !maps.Equal(body, want) { + t.Errorf("request body: %v", body) + } + if tc.status == 307 { + w.Header().Set("Location", "/redirected") + } + w.WriteHeader(tc.status) + fmt.Fprint(w, tc.body) + })) + defer srv.Close() + reg := providers.NewRegistry(nil) + reg.Register(providers.NewOpenAIProvider("minimax", "test-key", srv.URL+"/v1", tc.model)) + entry := MediaProviderEntry{Provider: "minimax", Model: tc.model, Enabled: true, MaxRetries: 3, Timeout: 1} + settings, err := json.Marshal(mediaProviderChain{Providers: []MediaProviderEntry{entry, entry}}) + if err != nil { + t.Fatal(err) + } + ctx := WithBuiltinToolSettings(WithToolWorkspace(t.Context(), t.TempDir()), BuiltinToolSettings{"create_image": settings}) + result := NewCreateImageTool(reg).Execute(ctx, map[string]any{"prompt": "a tree", "aspect_ratio": "16:9"}) + if posts.Load() != 1 { + t.Errorf("sent %d requests, want 1", posts.Load()) + } + if tc.wantError != "" { + if !result.IsError || !strings.Contains(result.ForLLM, tc.wantError) { + t.Fatalf("error: %s", result.ForLLM) + } + return + } + if result.IsError || len(result.Media) != 1 || result.Usage == nil || result.Usage.TotalTokens != 5 || result.Usage.ImageCount != 1 { + t.Fatalf("unexpected result: %+v", result) + } + out, err := os.ReadFile(result.Media[0].Path) + if err != nil { + t.Fatal(err) + } + if _, err := png.Decode(bytes.NewReader(out)); err != nil { + t.Fatalf("saved image: %v", err) + } + }) + } +} + +func TestMinimaxH3ChainTimeout(t *testing.T) { + reg := providers.NewRegistry(nil) + reg.Register(providers.NewOpenAIProvider("minimax", "test-key", "https://example.test/v1", "MiniMax-H3-Image")) + for _, tc := range []struct { + model string + configured, want int + }{ + {"MiniMax-H3-Image", 1, 600}, {"MiniMax-H3-Image-Highspeed", 900, 900}, {"image-01", 12, 12}, + } { + t.Run(tc.model, func(t *testing.T) { + entry := MediaProviderEntry{Provider: "minimax", Model: tc.model, Timeout: tc.configured, MaxRetries: 1} + before := time.Now() + _, err := ExecuteWithChain(t.Context(), []MediaProviderEntry{entry}, reg, func(ctx context.Context, _ credentialProvider, _, _ string, _ map[string]any) ([]byte, *providers.Usage, error) { + deadline, ok := ctx.Deadline() + expected := time.Duration(tc.want) * time.Second + if !ok || deadline.Before(before.Add(expected)) || deadline.After(time.Now().Add(expected)) { + t.Errorf("unexpected chain deadline %v for %ds", deadline, tc.want) + } + return nil, nil, nil + }) + if err != nil { + t.Fatal(err) + } + }) + } +} + +func TestMinimaxH3Endpoint(t *testing.T) { + for _, tc := range []struct{ base, want string }{ + {"https://api.minimax.io/v1", "https://api.minimax.io/v1/images/generations"}, + {"https://api.minimax.cn/v1/", "https://api.minimax.cn/v1/images/generations"}, + {"https://api.minimaxi.com/v1", "https://api.minimax.cn/v1/images/generations"}, + {"https://gateway.example/region/v1", "https://gateway.example/region/v1/images/generations"}, + } { + if got := minimaxH3Endpoint(tc.base); got != tc.want { + t.Errorf("endpoint for %s = %s, want %s", tc.base, got, tc.want) + } + } +} diff --git a/internal/tools/media_provider_chain.go b/internal/tools/media_provider_chain.go index afa10dcae9..b94bb66bd4 100644 --- a/internal/tools/media_provider_chain.go +++ b/internal/tools/media_provider_chain.go @@ -3,6 +3,7 @@ package tools import ( "context" "encoding/json" + "errors" "fmt" "io" "log/slog" @@ -197,6 +198,10 @@ func ExecuteWithChain( // Inject resolved provider type and the raw provider object into params so // callProvider can route correctly. Clone params to avoid mutating entry config. resolvedType := ResolveProviderType(p) + if resolvedType == "minimax" && isMinimaxH3Image(entry.Model) { + entry.Timeout = max(entry.Timeout, 600) + entry.MaxRetries = 1 + } callParams := make(map[string]any, len(entry.Params)+2) maps.Copy(callParams, entry.Params) callParams["_provider_type"] = resolvedType @@ -222,6 +227,12 @@ func ExecuteWithChain( lastErr = callErr + // A submitted H3 generation can complete and be billed after a disconnect. + // Retrying or falling through to another provider could generate twice. + if errors.Is(callErr, errMinimaxH3Submitted) { + return nil, callErr + } + // A budget refusal is a decision about this payload, not a sick // provider: falling through would hand the same bytes to the next // entry and bill them there instead.