99 lines
2.4 KiB
Go
99 lines
2.4 KiB
Go
package einograph
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"time"
|
||
|
||
"github.com/cloudwego/eino-ext/components/model/qwen"
|
||
"github.com/cloudwego/eino/components/model"
|
||
"github.com/gogf/gf/v2/util/gconv"
|
||
)
|
||
|
||
// NewChatModel component initialization function of node 'ChatModel1' in graph 'test'
|
||
func NewChatModel(ctx context.Context) (cm model.ChatModel, err error) {
|
||
// TODO Modify component configuration here.
|
||
config := &qwen.ChatModelConfig{
|
||
APIKey: "sk-4a8b82770bf74bc490eb3e4c5a8e2be9",
|
||
Model: "qwen-turbo",
|
||
BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", // 必须加!
|
||
MaxTokens: gconv.PtrInt(2000),
|
||
Temperature: gconv.PtrFloat32(float32(0.7))}
|
||
cm, err = qwen.NewChatModel(ctx, config)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return cm, nil
|
||
}
|
||
|
||
func GenerateRealImage(prompt string) (string, error) {
|
||
apiKey := "sk-4a8b82770bf74bc490eb3e4c5a8e2be9"
|
||
url := "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
|
||
|
||
body := map[string]any{
|
||
"model": "qwen-image",
|
||
"input": map[string]any{
|
||
"messages": []map[string]any{
|
||
{
|
||
"role": "user",
|
||
"content": []map[string]string{
|
||
{"type": "text", "text": prompt},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
"parameters": map[string]any{
|
||
"size": "1024*1364",
|
||
"n": 1,
|
||
"watermark": false,
|
||
},
|
||
}
|
||
|
||
payload, _ := json.Marshal(body)
|
||
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(payload))
|
||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||
req.Header.Set("Content-Type", "application/json")
|
||
|
||
client := &http.Client{Timeout: 30 * time.Second}
|
||
resp, err := client.Do(req)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
data, _ := io.ReadAll(resp.Body)
|
||
|
||
// ✅ 修复:plus 模型返回的字段是 image 不是 image_url
|
||
var result struct {
|
||
Output struct {
|
||
Choices []struct {
|
||
Message struct {
|
||
Content []struct {
|
||
Image string `json:"image"`
|
||
} `json:"content"`
|
||
} `json:"message"`
|
||
} `json:"choices"`
|
||
} `json:"output"`
|
||
Code string `json:"code"`
|
||
}
|
||
|
||
err = gconv.Struct(data, &result)
|
||
|
||
if len(result.Output.Choices) == 0 || result.Code != "" {
|
||
return "", fmt.Errorf("生成失败: %s", string(data))
|
||
}
|
||
|
||
// ✅ 修复:直接取 base64,不再下载
|
||
imgBase64 := result.Output.Choices[0].Message.Content[0].Image
|
||
if imgBase64 == "" {
|
||
return "", fmt.Errorf("图片为空")
|
||
}
|
||
|
||
// 解码 base64
|
||
return imgBase64, nil
|
||
}
|