Include chat, weather, image, travel, streaming ASR and text examples, shared model initialization, documentation, and existing tests. Co-authored-by: TRAE CLI <traecli@bytedance.com>
116 lines
3.0 KiB
Go
116 lines
3.0 KiB
Go
package provider
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"example.com/ueino/pkg/model"
|
|
)
|
|
|
|
// Image 请求图片接口并把结果保存到本地。
|
|
type Image struct {
|
|
endpoint string
|
|
model string
|
|
apiKey string
|
|
outputDir string
|
|
}
|
|
|
|
func NewImage(baseURL, modelName, apiKey, outputDir string) *Image {
|
|
return &Image{endpoint: strings.TrimRight(baseURL, "/") + "/images/generations", model: modelName, apiKey: apiKey, outputDir: outputDir}
|
|
}
|
|
|
|
func (i *Image) Generate(ctx context.Context, prompt string) (*model.ImageResult, error) {
|
|
if strings.TrimSpace(prompt) == "" {
|
|
return nil, fmt.Errorf("生图提示词不能为空")
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
|
|
defer cancel()
|
|
headers := map[string]string{}
|
|
if i.apiKey != "" {
|
|
headers["Authorization"] = "Bearer " + i.apiKey
|
|
}
|
|
var response model.ImageGenerationResponse
|
|
if err := PostJSON(ctx, i.endpoint, headers, model.ImageGenerationRequest{Model: i.model, Prompt: prompt, N: 1}, &response); err != nil {
|
|
return nil, fmt.Errorf("生成图片失败: %w", err)
|
|
}
|
|
if len(response.Data) == 0 {
|
|
return nil, fmt.Errorf("生图接口没有返回图片")
|
|
}
|
|
data := response.Data[0]
|
|
var content []byte
|
|
var err error
|
|
switch {
|
|
case data.Base64 != "":
|
|
content, err = base64.StdEncoding.DecodeString(data.Base64)
|
|
case data.URL != "":
|
|
content, err = downloadImage(ctx, data.URL)
|
|
default:
|
|
return nil, fmt.Errorf("生图结果缺少图片数据或 URL")
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("读取图片失败: %w", err)
|
|
}
|
|
extension := ""
|
|
switch http.DetectContentType(content) {
|
|
case "image/png":
|
|
extension = ".png"
|
|
case "image/jpeg":
|
|
extension = ".jpg"
|
|
case "image/webp":
|
|
extension = ".webp"
|
|
default:
|
|
return nil, fmt.Errorf("图片格式不支持,仅支持 PNG、JPEG 和 WebP")
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
directory, err := filepath.Abs(i.outputDir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := os.MkdirAll(directory, 0755); err != nil {
|
|
return nil, fmt.Errorf("创建图片目录失败: %w", err)
|
|
}
|
|
file, err := os.CreateTemp(directory, "image-*"+extension)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("创建图片文件失败: %w", err)
|
|
}
|
|
_, writeErr := file.Write(content)
|
|
closeErr := file.Close()
|
|
if writeErr == nil {
|
|
writeErr = closeErr
|
|
}
|
|
if writeErr == nil {
|
|
writeErr = ctx.Err()
|
|
}
|
|
if writeErr != nil {
|
|
os.Remove(file.Name())
|
|
return nil, fmt.Errorf("保存图片失败: %w", writeErr)
|
|
}
|
|
return &model.ImageResult{Path: file.Name()}, nil
|
|
}
|
|
|
|
func downloadImage(ctx context.Context, url string) ([]byte, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 下载地址可能属于另一服务,不转发模型接口的认证信息。
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return nil, fmt.Errorf("图片下载返回 %s", resp.Status)
|
|
}
|
|
return io.ReadAll(resp.Body)
|
|
}
|