Go SDK 接入指南
更新时间:
智作工坊 SpeedPix Go SDK,提供简洁易用的 AI 图像生成和处理工作流接口。
资源链接
资源 | 链接 | 描述 |
Go 包 | 最新版本和历史版本 | |
开源仓库 | 源码、Issue、贡献代码 |
查看 API 文档
授权
获取 API 凭据
创建应用获取
app_key
和app_secret
调用 OpenAPI
准备 Go 环境
确保 Go 1.19+
go version
配置环境变量
# 设置 API 凭据(推荐方式)
export SPEEDPIX_APP_KEY="your-app-key"
export SPEEDPIX_APP_SECRET="your-app-secret"
export SPEEDPIX_ENDPOINT="https://your-endpoint.com" # 可选
安装依赖
go mod init your-project
go get github.com/aliyun/speedpix-go
准备一个已经发布的工作流
在智作工坊控制台中:
参考 工作流管理
创建或选择一个 AI 工作流,可以将以下示例工作流拖入工作流编辑器
这是一个将输入商品图变成白底图的工作流 SDK 测试案例.json ,该工作流会自动从用户输入图片抽取商品主体,然后根据用户输入文本生成商品白底图
示范参数:
输入文本
输入图片
输出结果
测试文本
发布工作流并获取
workflow_id
发布时选择 #1 号节点的 image 字段以及 #6 号节点的 text 作为输入字段
选择 #10 号节点的 images 作为输出字段
点击提交发布,此时会产生一个 v1 版本,点击右侧别名管理,新建一个 main 别名,映射到 v1 版本,后续我们可以使用该别名调用该工作流,如果需要更新版本,只用在这里切换别名即可,不用代码层变更。
记录工作流的输入、输出格式要求
复制示例代码
创建 main.go
文件:
package main
import (
"context"
"fmt"
"log"
"github.com/aliyun/speedpix-go"
)
// 定义结果数据结构
type ImageResult struct {
Image *speedpix.ImageFile `json:"images"` // 单个 ImageFile
Info string `json:"info"`
}
func main() {
// 初始化客户端(自动从环境变量读取配置)
client, err := speedpix.NewClient(speedpix.WithAllFromEnv())
if err != nil {
log.Fatal(err)
}
// 或直接指定参数
// client, err := speedpix.NewClient(
// speedpix.WithAppKey("your-app-key"),
// speedpix.WithAppSecret("your-app-secret"),
// )
ctx := context.Background()
// 运行 AI 工作流(类型安全版本)
result, err := speedpix.RunTyped[ImageResult](ctx, client, speedpix.RunOptions{
WorkflowID: "your_workflow_id",
AliasID: stringPtr("main"), // 可选,默认为 "main"
Input: map[string]interface{}{
"text": "一幅美丽的山水画",
"image": "./input.jpg", // 网络 URL
// 可选:包含文件输入(SDK 会自动处理文件上传)
// "input_image": "/path/to/input.jpg", // 本地文件路径
// "reference_image": file, // io.Reader 对象
// "style_image": "https://example.com/style.jpg", // 网络 URL
},
})
if err != nil {
log.Fatal(err)
}
// 保存结果
if result.Image != nil {
err := result.Image.Save("result.png")
if err != nil {
log.Fatal(err)
}
fmt.Println("图片已保存为 result.png")
fmt.Printf("信息: %s\n", result.Info)
fmt.Printf("图片URL: %s\n", result.Image.URL)
}
}
// 辅助函数
func stringPtr(s string) *string {
return &s
}
执行测试
# 运行项目
go run main.go
# 验证安装
go list -m github.com/aliyun/speedpix-go
# 检查生成的文件
ls -la result.png
更多使用方式
方式1:最简单(推荐新手)
// 定义自定义输出结构
type ImageResult struct {
Images [ ]string `json:"images"` // 图片 URL 数组
Info string `json:"info"` // 附加信息
}
// 纯文本输入
result, err := speedpix.RunTyped[ImageResult](ctx, client, speedpix.RunOptions{
WorkflowID: "your-workflow-id",
Input: map[string]interface{}{
"prompt": "一个美丽的风景",
},
})
// 包含文件输入
result, err := speedpix.RunTyped[ImageResult](ctx, client, speedpix.RunOptions{
WorkflowID: "image-enhancement-workflow",
Input: map[string]interface{}{
"prompt": "增强图片质量",
"input_image": "/path/to/image.jpg", // 本地文件自动上传
},
})
方式2:完全控制(高级用户)
// 创建预测但不等待(支持文件输入)
prediction, err := client.Predictions.Create(ctx, speedpix.CreatePredictionOptions{
WorkflowID: "your-workflow-id",
Input: map[string]interface{}{
"prompt": "一个复杂的场景",
"base_image": "/path/to/base.jpg", // 本地文件
"style_ref": reader, // io.Reader
"mask_url": "https://cdn.example.com/mask.png", // 网络 URL
},
})
// 手动等待完成
completed, err := prediction.Wait(ctx)
fmt.Println("输出:", completed.Output)
方式3:异步处理
// 创建预测任务但不等待(AliasID 自动默认为 "main")
prediction, err := client.Predictions.Create(ctx, speedpix.CreatePredictionOptions{
WorkflowID: "your-workflow-id",
Input: map[string]interface{}{
"prompt": "一个美丽的风景",
},
// AliasID 可选,不提供时默认为 "main"
})
if err != nil {
log.Fatal(err)
}
// 等待完成
prediction, err = prediction.Wait(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("输出:", prediction.Output)
资源配置
共享算力 vs 独享资源
智作工坊支持两种资源类型:
共享算力:默认使用,成本较低,适合一般业务场景
独享资源:推荐对延迟和成功率敏感的业务使用,提供更稳定的性能保障
配置方式
默认情况下,如果不指定 ResourceConfigID
,系统会使用共享算力资源。如果您对延迟和成功率有较高要求,推荐配置独享资源。
// 使用共享算力(默认)
output, err := client.Run(ctx, speedpix.RunOptions{
WorkflowID: "your-workflow-id",
Input: map[string]interface{}{
"prompt": "一个美丽的风景",
},
// ResourceConfigID 不指定时自动使用共享算力
})
// 使用独享资源
output, err := client.Run(ctx, speedpix.RunOptions{
WorkflowID: "your-workflow-id",
ResourceConfigID: "your-dedicated-resource-id", // 指定独享资源ID
Input: map[string]interface{}{
"prompt": "一个美丽的风景",
},
})
// 在创建预测时指定独享资源
prediction, err := client.Predictions.Create(ctx, speedpix.CreatePredictionOptions{
WorkflowID: "your-workflow-id",
ResourceConfigID: "your-dedicated-resource-id",
Input: map[string]interface{}{
"prompt": "一个美丽的风景",
},
})
相关文档
详细 API 参考
客户端配置选项
// NewClient 创建客户端,支持以下选项:
client, err := speedpix.NewClient(
// 必需参数
speedpix.WithAppKey("your-app-key"), // API 密钥
speedpix.WithAppSecret("your-app-secret"), // API 密钥
// 可选参数
speedpix.WithEndpoint("custom-endpoint"), // 自定义端点,默认: https://openai.edu-aliyun.com
speedpix.WithTimeout(60*time.Second), // 请求超时,默认: 30s
speedpix.WithUserAgent("my-app/1.0.0"), // 用户代理
speedpix.WithHTTPClient(customClient), // 自定义 HTTP 客户端
// 从环境变量读取所有配置
speedpix.WithAllFromEnv(), // 读取 SPEEDPIX_* 环境变量
)
Run API - 直接运行工作流
// Run 直接运行工作流并等待结果
output, err := client.Run(ctx, speedpix.RunOptions{
// 必需参数
WorkflowID string // 工作流 ID
// 工作流输入
Input map[string]interface{} // 输入参数,根据工作流要求设置
// 可选参数
AliasID *string // 工作流别名,默认: "main"
VersionID *string // 工作流版本 ID
RandomiseSeeds *bool // 是否随机化种子
ReturnTempFiles *bool // 是否返回临时文件
ResourceConfigID string // 资源配置 ID
PollingInterval time.Duration // 轮询间隔,默认: 1s
})
// RunTyped 类型安全版本
result, err := speedpix.RunTyped[YourResultType](ctx, client, options)
Predictions API - 预测任务管理
// Create 创建预测任务
prediction, err := client.Predictions.Create(ctx, speedpix.CreatePredictionOptions{
WorkflowID string // 工作流 ID
Input map[string]interface{} // 输入参数
AliasID *string // 工作流别名,默认: "main"
VersionID *string // 工作流版本 ID
RandomiseSeeds *bool // 是否随机化种子
ReturnTempFiles *bool // 是否返回临时文件
ResourceConfigID string // 资源配置 ID
})
// CreateTyped 类型安全版本
prediction, err := speedpix.CreateTypedPrediction[YourResultType](ctx, client, options)
// Get 获取预测任务状态
prediction, err := client.Predictions.Get(ctx, predictionID)
// Wait 等待预测完成
prediction, err := prediction.Wait(ctx, speedpix.WaitOptions{
PollingInterval time.Duration // 轮询间隔,默认: 1s
})
// Cancel 取消预测任务
err := client.Predictions.Cancel(ctx, predictionID)
Files API - 文件管理
// Create 上传文件
file, err := client.Files.Create(ctx, "/path/to/file.jpg")
// CreateFromReader 从 Reader 上传
file, err := client.Files.CreateFromReader(ctx, reader, "filename.jpg")
// Get 获取文件信息
file, err := client.Files.Get(ctx, fileID)
// Delete 删除文件
err := client.Files.Delete(ctx, fileID)
// 文件对象属性
type File struct {
ID string // 文件 ID
URL string // 访问 URL
AccessURL string // 访问 URL(别名)
CreatedAt time.Time // 创建时间
Size int64 // 文件大小
MimeType string // MIME 类型
}
增强文件类型支持
// ImageFile - 图片文件
type ImageFile struct {
*FileOutput
Width int // 图片宽度
Height int // 图片高度
Format string // 图片格式 (jpg, png, etc.)
DPI int // 分辨率
ColorSpace string // 色彩空间
Metadata map[string]string // 元数据
}
// 图片特有方法
img.GetAspectRatio() float64 // 获取宽高比
img.IsSquare() bool // 是否为正方形
img.IsPortrait() bool // 是否为竖向
img.IsLandscape() bool // 是否为横向
// VideoFile - 视频文件
type VideoFile struct {
*FileOutput
Duration time.Duration // 视频时长
Width int // 视频宽度
Height int // 视频高度
Format string // 视频格式
Codec string // 编解码器
FrameRate float64 // 帧率
HasAudio bool // 是否包含音频
AudioCodec string // 音频编解码器
}
// 视频特有方法
video.IsHD() bool // 是否为高清 (≥720p)
video.Is4K() bool // 是否为 4K (≥2160p)
video.GetResolutionString() string // 获取分辨率字符串
// AudioFile - 音频文件
type AudioFile struct {
*FileOutput
Duration time.Duration // 音频时长
SampleRate int // 采样率
Bitrate int // 比特率
Channels int // 声道数
Format string // 音频格式
}
// DocumentFile - 文档文件
type DocumentFile struct {
*FileOutput
Pages int // 页数
Language string // 语言
Author string // 作者
CreatedAt time.Time // 创建时间
}
预定义输出类型
以下类型主要用于 SDK 内部处理,用户通常定义自己的输出结构:
// ImageOutput - 图像生成输出(SDK 内部使用)
type ImageOutput struct {
Images [ ]*ImageFile `json:"images"` // 生成的图片数组
}
// TextOutput - 文本生成输出(SDK 内部使用)
type TextOutput struct {
Text string `json:"text"` // 生成的文本
}
// VideoOutput - 视频生成输出(SDK 内部使用)
type VideoOutput struct {
Videos [ ]*VideoFile `json:"videos"` // 生成的视频数组
}
// AudioOutput - 音频生成输出(SDK 内部使用)
type AudioOutput struct {
Audios [ ]*AudioFile `json:"audios"` // 生成的音频数组
}
// MultiModalOutput - 多模态输出(SDK 内部使用)
type MultiModalOutput struct {
Images [ ]*ImageFile `json:"images"` // 图片
Text string `json:"text"` // 文本
}
// CustomResult - 自定义结果(基于 map)
type CustomResult map[string]interface{}
用户自定义输出结构示例
实际使用中,用户应该根据工作流的具体输出定义自己的结构:
// 基础图片结果(推荐)
type ImageResult struct {
Images [ ]string `json:"images"` // 图片 URL 数组
Info string `json:"info"` // 附加信息
}
// 基础视频结果
type VideoResult struct {
Video string `json:"video"` // 视频 URL
Info string `json:"info"` // 附加信息
}
// 基础文本结果
type TextResult struct {
Text string `json:"text"` // 生成的文本
Info string `json:"info"` // 附加信息
}
// 复杂的输出结构(可选)
type DetailedResult struct {
MainImage string `json:"main_image"`
Thumbnails [ ]string `json:"thumbnails"`
Metadata map[string]string `json:"metadata"`
ProcessTime float64 `json:"process_time"`
}
任务状态
// Prediction 预测任务状态
type Prediction struct {
ID string // 任务 ID
Status string // 状态: "starting", "processing", "succeeded", "failed", "canceled"
Output interface{} // 输出结果
Error *string // 错误信息
Logs string // 运行日志
Metrics *Metrics // 运行指标
CreatedAt time.Time // 创建时间
StartedAt *time.Time // 开始时间
CompletedAt *time.Time // 完成时间
}
// Metrics 运行指标
type Metrics struct {
PredictTime float64 // 预测耗时(秒)
TotalTime float64 // 总耗时(秒)
}
错误类型
// PredictionError 预测错误
type PredictionError struct {
Prediction *Prediction // 关联的预测任务
Message string // 错误消息
}
// APIError API 错误
type APIError struct {
Status int // HTTP 状态码
Code string // 错误代码
Message string // 错误消息
}
使用场景示例
文生图
type ImageResult struct {
Images [ ]string `json:"images"` // 生成的图片 URL 数组
Info string `json:"info"` // 附加信息
}
result, err := speedpix.RunTyped[ImageResult](ctx, client, speedpix.RunOptions{
WorkflowID: "text-to-image-workflow",
Input: map[string]interface{}{
"prompt": "一个美丽的日落风景",
"negative_prompt": "low quality, blurry",
"width": 1024,
"height": 768,
"steps": 20,
"guidance_scale": 7.5,
},
})
图生图
type ImageResult struct {
Images [ ]string `json:"images"` // 转换后的图片 URL 数组
Info string `json:"info"` // 附加信息
}
result, err := speedpix.RunTyped[ImageResult](ctx, client, speedpix.RunOptions{
WorkflowID: "image-to-image-workflow",
Input: map[string]interface{}{
"image": "/path/to/input.jpg", // 自动上传
"prompt": "转换为油画风格",
"strength": 0.8,
},
})
图转视频
type VideoResult struct {
Video string `json:"video"` // 生成的视频 URL
Info string `json:"info"` // 附加信息
}
result, err := speedpix.RunTyped[VideoResult](ctx, client, speedpix.RunOptions{
WorkflowID: "image-to-video-workflow",
Input: map[string]interface{}{
"image": "/path/to/image.jpg",
"duration": 5.0,
"fps": 24,
"motion_strength": 0.5,
},
})
批量处理
type ImageResult struct {
Images [ ]string `json:"images"` // 生成的图片 URL 数组
Info string `json:"info"` // 附加信息
}
var predictions [ ]*speedpix.TypedPrediction[ImageResult]
// 创建多个任务
for i, prompt := range prompts {
pred, err := speedpix.CreateTypedPrediction[ImageResult](ctx, client, speedpix.CreatePredictionOptions{
WorkflowID: "batch-workflow",
Input: map[string]interface{}{
"prompt": prompt,
"batch_id": i,
},
})
if err == nil {
predictions = append(predictions, pred)
}
}
// 等待所有任务完成
for i, pred := range predictions {
completed, err := pred.Wait(ctx)
if err == nil {
fmt.Printf("任务 %d 完成,生成了 %d 张图片\n", i, len(completed.Output.Images))
}
}
高级配置
自定义 HTTP 客户端
httpClient := &http.Client{
Timeout: 10 * time.Minute,
Transport: &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
},
}
client, err := speedpix.NewClient(
speedpix.WithHTTPClient(httpClient),
speedpix.WithAllFromEnv(),
)
重试机制
func runWithRetry(ctx context.Context, client *speedpix.Client, options speedpix.RunOptions, maxRetries int) (interface{}, error) {
var lastErr error
for i := 0; i < maxRetries; i++ {
result, err := client.Run(ctx, options)
if err == nil {
return result, nil
}
lastErr = err
if i < maxRetries-1 {
time.Sleep(time.Duration(i+1) * time.Second) // 指数退避
}
}
return nil, fmt.Errorf("达到最大重试次数 %d: %w", maxRetries, lastErr)
}
监控和日志
func runWithMonitoring(ctx context.Context, client *speedpix.Client, options speedpix.RunOptions) (interface{}, error) {
start := time.Now()
log.Printf("开始运行工作流: %s", options.WorkflowID)
result, err := client.Run(ctx, options)
duration := time.Since(start)
if err != nil {
log.Printf("工作流失败: %s, 耗时: %v, 错误: %v", options.WorkflowID, duration, err)
return nil, err
}
log.Printf("工作流完成: %s, 耗时: %v", options.WorkflowID, duration)
return result, nil
}
现在你已经掌握了 SpeedPix Go SDK 的完整使用方法!
该文章对您有帮助吗?