An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
✨ Support MiniMax image generation
octo-patch030fb0053698
diff --git a/kernel/util/minimax_image.go b/kernel/util/minimax_image.gonew file mode 100644index 0000000000..e0822df9e7--- /dev/null+++ b/kernel/util/minimax_image.go@@ -0,0 +1,128 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strconv"+ "strings"++ "github.com/sashabaranov/go-openai"+)++func isMiniMaxImageEndpoint(baseURL string) bool {+ u, err := url.Parse(baseURL)+ if err != nil || u.Scheme != "https" || strings.TrimRight(u.Path, "/") != "/v1" {+ return false+ }+ host := strings.ToLower(u.Hostname())+ return host == "api.minimax.io" || host == "api.minimaxi.com"+}++type miniMaxImageTransport struct {+ base openai.HTTPDoer+}++func (t *miniMaxImageTransport) Do(req *http.Request) (*http.Response, error) {+ if req.Method != http.MethodPost || !strings.HasSuffix(req.URL.Path, "/images/generations") {+ return t.base.Do(req)+ }+ var input struct {+ Model string `json:"model"`+ Prompt string `json:"prompt"`+ Size string `json:"size"`+ N int `json:"n"`+ }+ err := json.NewDecoder(req.Body).Decode(&input)+ req.Body.Close()+ if err != nil {+ return nil, err+ }+ payload := map[string]any{+ "model": input.Model, "prompt": input.Prompt, "n": input.N,+ "response_format": "url", "prompt_optimizer": true,+ }+ if input.Size == "" || input.Size == "auto" {+ payload["aspect_ratio"] = "1:1"+ } else {+ dimensions := strings.Split(input.Size, "x")+ if len(dimensions) != 2 {+ return nil, errors.New("MiniMax image size must be WIDTHxHEIGHT")+ }+ width, widthErr := strconv.Atoi(dimensions[0])+ height, heightErr := strconv.Atoi(dimensions[1])+ if widthErr != nil || heightErr != nil || width <= 0 || height <= 0 {+ return nil, errors.New("MiniMax image dimensions must be positive integers")+ }+ payload["width"], payload["height"] = width, height+ }+ body, err := json.Marshal(payload)+ if err != nil {+ return nil, err+ }+ converted := req.Clone(req.Context())+ converted.URL.Path = strings.TrimSuffix(req.URL.Path, "/images/generations") + "/image_generation"+ converted.URL.RawPath = ""+ converted.Body = io.NopCloser(bytes.NewReader(body))+ converted.ContentLength = int64(len(body))+ converted.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil }+ resp, err := t.base.Do(converted)+ if err != nil {+ return nil, err+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ resp.Body.Close()+ return nil, fmt.Errorf("MiniMax image request failed with HTTP status %d", resp.StatusCode)+ }+ var output struct {+ Data struct {+ URLs []string `json:"image_urls"`+ } `json:"data"`+ BaseResp *struct {+ StatusCode int `json:"status_code"`+ } `json:"base_resp"`+ }+ err = json.NewDecoder(io.LimitReader(resp.Body, 1024*1024)).Decode(&output)+ resp.Body.Close()+ if err != nil {+ return nil, err+ }+ if output.BaseResp == nil || output.BaseResp.StatusCode != 0 {+ return nil, errors.New("MiniMax image generation failed")+ }+ if len(output.Data.URLs) == 0 || output.Data.URLs[0] == "" {+ return nil, errors.New("MiniMax image model returned no image")+ }+ data := make([]map[string]string, 0, len(output.Data.URLs))+ for _, imageURL := range output.Data.URLs {+ data = append(data, map[string]string{"url": imageURL})+ }+ body, err = json.Marshal(map[string]any{"data": data})+ if err != nil {+ return nil, err+ }+ resp.Body = io.NopCloser(bytes.NewReader(body))+ resp.ContentLength = int64(len(body))+ resp.Header.Set("Content-Length", strconv.Itoa(len(body)))+ return resp, nil+}diff --git a/kernel/util/minimax_image_test.go b/kernel/util/minimax_image_test.gonew file mode 100644index 0000000000..bb28375986--- /dev/null+++ b/kernel/util/minimax_image_test.go@@ -0,0 +1,110 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/sashabaranov/go-openai"+)++func TestMiniMaxImageEndpoints(t *testing.T) {+ for endpoint, want := range map[string]bool{+ "https://api.minimax.io/v1": true,+ "https://api.minimaxi.com/v1/": true,+ "https://api.minimax.io.example.com/v1": false,+ "https://example.com/v1": false,+ "http://api.minimax.io/v1": false,+ "https://api.minimax.io/anthropic": false,+ } {+ if got := isMiniMaxImageEndpoint(endpoint); got != want {+ t.Errorf("endpoint %q: got %v, want %v", endpoint, got, want)+ }+ }+}++func TestMiniMaxImageRequestAndResponse(t *testing.T) {+ for _, size := range []string{"auto", "1024x1536"} {+ t.Run(size, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/image_generation" || r.Method != http.MethodPost || r.Header.Get("Authorization") != "Bearer test" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ }+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ if body["model"] != "image-01" || body["prompt"] != "A header" || body["n"] != float64(1) || body["response_format"] != "url" || body["prompt_optimizer"] != true {+ t.Errorf("unexpected payload: %#v", body)+ }+ if size == "auto" && body["aspect_ratio"] != "1:1" {+ t.Errorf("missing default aspect ratio: %#v", body)+ }+ if size != "auto" && (body["width"] != float64(1024) || body["height"] != float64(1536)) {+ t.Errorf("incorrect dimensions: %#v", body)+ }+ for _, key := range []string{"size", "quality", "output_format"} {+ if _, present := body[key]; present {+ t.Errorf("unsupported field %s was sent", key)+ }+ }+ w.Header().Set("Content-Type", "application/json")+ fmt.Fprint(w, `{"base_resp":{"status_code":0},"data":{"image_urls":["https://example.com/generated.png"]}}`)+ }))+ defer server.Close()+ config := openai.DefaultConfig("test")+ config.BaseURL = server.URL + "/v1"+ config.HTTPClient = &miniMaxImageTransport{base: server.Client()}+ client := openai.NewClientWithConfig(config)+ response, err := client.CreateImage(context.Background(), openai.ImageRequest{Model: "image-01", Prompt: "A header", N: 1, Size: size, Quality: "auto", OutputFormat: "png"})+ if err != nil {+ t.Fatal(err)+ }+ if len(response.Data) != 1 || response.Data[0].URL != "https://example.com/generated.png" {+ t.Fatalf("unexpected image response: %#v", response)+ }+ })+ }+}++func TestMiniMaxImageFailures(t *testing.T) {+ for _, body := range []string{+ `{"base_resp":{"status_code":1004},"data":{"image_urls":["https://example.com/image.png"]}}`,+ `{"base_resp":{"status_code":0},"data":{"image_urls":[]}}`,+ `{"data":{"image_urls":["https://example.com/image.png"]}}`,+ `invalid`,+ } {+ t.Run(body, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprint(w, body)+ }))+ defer server.Close()+ config := openai.DefaultConfig("test")+ config.BaseURL = server.URL + "/v1"+ config.HTTPClient = &miniMaxImageTransport{base: server.Client()}+ _, err := openai.NewClientWithConfig(config).CreateImage(context.Background(), openai.ImageRequest{Model: "image-01", Prompt: "A header", N: 1})+ if err == nil {+ t.Fatal("expected image generation to fail")+ }+ })+ }+}diff --git a/kernel/util/openai.go b/kernel/util/openai.goindex 2b39085126..e63727c11d 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -839,8 +839,15 @@ func NewOpenAIImageAdapter(apiKey, apiBaseURL, model string, timeout int) *OpenAif timeout < 1 {timeout = 30}+ client := NewOpenAIClientWithModel(apiKey, apiBaseURL, model)+ if isMiniMaxImageEndpoint(apiBaseURL) {+ config := openai.DefaultConfig(apiKey)+ config.BaseURL = apiBaseURL+ config.HTTPClient = &miniMaxImageTransport{base: httpclient.NewUserAgentClient(nil)}+ client = openai.NewClientWithConfig(config)+ }return &OpenAIImageAdapter{- client: NewOpenAIClientWithModel(apiKey, apiBaseURL, model),+ client: client,model: model,timeout: time.Duration(timeout) * time.Second,}