All Products
Search
Document Center

Platform For AI:Use AI Portrait SDK for Go

Last Updated:Mar 11, 2026

Call AI Portrait APIs with Go SDK to train custom LoRA models and generate portraits from templates.

Prerequisites

  • Go environment is ready.

  • 5 to 20 training images and 1 template image are prepared for model training and portrait creation. Supported formats: .jpg, .jpeg, and .png. Each image must be larger than 512×512 pixels.

    • For solo portraits: Template image must contain one face, and all training images must belong to the same person.

    • For group portraits: Template image must contain multiple faces matching the number of model_id values specified during model training.

Preparations

  1. Environment dependency: Go 1.18 or later.

  2. Install Go SDK locally.

    1. Create a project: go mod init project name

    2. Download the SDK: go get github.com/aliyun/aliyun-pai-aiservice-go-sdk

    3. Import the SDK: import "github.com/aliyun/aliyun-pai-aiservice-go-sdk"

  3. Initialize the client.

    1. Set HOST, AppId, and Token as environment variables.

      export HOST="http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com"
      export AppId=xxx
      export Token=xxxxxxxxx

      Parameter

      Description

      HOST

      Server address: http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

      AppId

      View your AppId on the AI Portrait page after activation.

      Token

      View your Token on the AI Portrait page after activation.

    2. Initialize the client.

      host := os.Getenv("Host")
      appId := os.Getenv("AppId")
      token := os.Getenv("Token")
      
      client := sdk.NewClient(host, appId, token)

Sample code

AI Portrait is a resource-intensive service consisting of two main steps: model training and portrait creation. Model training typically takes several minutes, while portrait creation completes in tens of seconds. The following figure shows the API call workflow.

image

The following sections provide sample request and response code for each API, along with end-to-end examples.

Image check request (client.AIGCApi.AigcImageCheck)

  • Sample request code:

    package main
    
    import (
    	"fmt"
    	"log"
    	"os"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
      // Get HOST, AppId, and Token from environment variables.
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    
    	// Check image list.
    	images := []string{"https://train/0.jpg","https://train/1.jpg","https://train/2.jpg","https://train/3.jpg"}
    
    	response, err := client.AIGCApi.AigcImageCheck(images, "", nil)
    
    	fmt.Println(response)
    
    	if err != nil {
    		log.Fatal(err)
    		return
    	}
    
    	if response.Code != "OK" {
    		log.Fatal("response error:%v", response)
    		return
    	}
    
    	// Traverse image check results.
    	for _, result := range response.Data.CheckResults {
    		fmt.Printf("code=%d\tfrontal=%v\turl=%s\n", result.Code, result.Frontal, result.Url)
    	}
    }
    

    Parameters:

    Parameter

    Description

    Type

    images

    Image URLs (comma-separated)

    []string

  • Response description:

    The response returns an AIGCImageCheckResponse object containing these fields:

    Parameter

    Description

    Type

    RequestId

    Request ID

    string

    Code

    Request status code: OK or error

    string

    Message

    Detailed request status. Returns "success" on success; otherwise returns error details

    string

    Data

    Returned data details

    AIGCImageCheckData

    Data field: An AIGCImageCheckData object.

    Parameter

    Description

    Type

    CheckResults

    Detection result for each input image. Each image corresponds to a dictionary with three keys: url, message, and frontal. These represent image URL, detection details, and whether the image is front-facing

    List<AIGCImageCheckResult>

    CostTime

    Server-side compute time spent on this API call.

    float64

    Images

    List of verified image URLs.

    List<String>

    RequestId

    Request ID (same as the top-level request_id).

    String

    check_results field: An AIGCImageCheckResult object.

    Parameter

    Description

    Type

    Code

    Request status code indicating completion: 0 or 1.

    Detection result for each input image.

    int

    Frontal

    Image detection details and whether it is front-facing.

    bool

    Message

    Status information.

    string

    Url

    Image URL.

    string

    Summary of check_results messages:

    message

    Status code

    Description

    success

    1

    The requirements are met.

    Image decode error.

    2

    The image cannot be downloaded or decoded.

    Number of face is not 1.

    3

    The number of faces in the image is not 1.

    Image detect error.

    4

    Face detection failed.

    Image encoding error.

    5

    Failed to encode the face into a feature vector. This error usually occurs if no face is detected.

    This photo is not the same person in photos.

    6

    The face in this image does not match the faces in the other images.

Model training initiation (client.AIGCApi.AigcImagesTrain)

  • Stable Diffusion 1.5 training

    package main
    
    import (
    	"fmt"
    	"log"
    	"os"
    	"time"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
      // Get HOST, AppId, and Token from environment variables.
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    
    	images := []string{"https://train/0.jpg","https://train/1.jpg","https://train/2.jpg","https://train/3.jpg"}
    
    	response, err := client.AIGCApi.AigcImagesTrain(images, "", nil)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Job ID
    	jobId := response.Data.JobId
    	modelId := response.Data.ModelId
    	fmt.Println(jobId)
    
    	jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    	fmt.Println(jobResponse.Data.Job.Message)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	for {
    		jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    		fmt.Println(jobResponse.Data.Job.Result)
    		if err != nil {
    			log.Fatal("get job fail", err)
    		}
    
    		if jobResponse.Data.Job.State == sdk.JOB_STATE_WAIT {
    			fmt.Println("job running")
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_SUCCESS { // job success
    			fmt.Println(jobResponse)
    			fmt.Println("job success")
    			break
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_FAILED {
    			log.Fatal("job fail", err)
    			return
    		}
    
    		time.Sleep(30 * time.Second)
    	}
    	fmt.Println(modelId)
    
    }
    

    Parameter Name

    Description

    Type

    images

    Training image URLs

    []string

  • Stable Diffusion XL (SDXL) training

    To use SDXL, contact your account manager to activate the service. Then, specify the model name.

    SDXL supports both portrait training and scene LoRA training.

    The training for both is specified by the configuration parameters.

    package main
    
    import (
    	"fmt"
    	"log"
    	"os"
    	"time"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
      // Get HOST, AppId, and Token from environment variables.
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    
    	images := []string{"https://train/0.jpg","https://train/1.jpg","https://train/2.jpg","https://train/3.jpg"}
    
    	modelName := "train_xl"
    	configure := make(map[string]interface{}, 10)
    	configure["train_scene_lora_bool"] = false
    	configure["scene_lora_prompts"] = []string{"a photography of a woman with long blonde hair and a white dress",
    		"a photography of a woman in a pink dress posing for a picture",
    		"a photography of a woman in a black dress with a white background",
    		"a photography of a woman with a frilly collar and suspenders",
    		"a photography of a woman with a white dress and a white headpiece"}
    
    	response, err := client.AIGCApi.AigcImagesTrain(images, modelName, configure)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Job ID
    	jobId := response.Data.JobId
    	modelId := response.Data.ModelId
    	fmt.Println(jobId)
    
    	jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    	fmt.Println(jobResponse.Data.Job.Message)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	for {
    		jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    		fmt.Println(jobResponse.Data.Job.Result)
    		if err != nil {
    			log.Fatal("get job fail", err)
    		}
    
    		if jobResponse.Data.Job.State == sdk.JOB_STATE_WAIT {
    			fmt.Println("job running")
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_SUCCESS { // job success
    			fmt.Println(jobResponse)
    			fmt.Println("job success")
    			break
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_FAILED {
    			log.Fatal("job fail", err)
    			return
    		}
    
    		time.Sleep(30 * time.Second)
    	}
    	fmt.Println(modelId)
    
    }
    

    Parameter Name

    Description

    Type

    images

    List of training image URLs.

    []string

    modelName

    Model name. Set to train_xl for SDXL.

    string

    configure

    Parameter configuration (default: nil)

    map[string]interface{}

    Parameter in configure

    Description

    Type

    Required

    Default

    Valid values

    train_scene_lora_bool

    Whether to train scene LoRA.

    bool

    No

    False

    True, False

    scene_lora_prompts

    Prompts for scene LoRA training.

    Required for scene LoRA training. List length must match the number of image URLs.

    []string

    No

    []

    N/A

  • Response parsing

    The service returns an AIGCImageTrainResponse object.

    Parameter

    Description

    Type

    RequestId

    Request ID.

    string

    Code

    Request status code indicating completion: OK or error.

    string

    Message

    Detailed request status. Returns success on success; otherwise, returns specific details.

    string

    Data

    Details of returned data.

    AIGCImageTrainData

    Fields of the AIGCImageTrainData object

    Parameter Name

    Description

    Type

    jobId

    Job ID.

    int32

    modelId

    Model ID for this training session, a 36-character string.

    string

    Save the jobId to query the training results.

    Save the modelId to request portrait creation.

Training result query (client.JobApi.GetAsyncJobWithId)

  • Sample request code

    package main
    
    import (
    	"fmt"
    	"log"
    	"os"
    	"time"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
    	// Get HOST, AppId, and Token from environment variables.
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    
    	// Job ID
    	var jobId int32 = xxxxxx
    
    	for {
    		jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    		if err != nil {
    			log.Fatal("get job fail", err)
    		}
    
    		if jobResponse.Data.Job.State == sdk.JOB_STATE_WAIT {
    			fmt.Println("job running")
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_SUCCESS { // job success
    			fmt.Println(jobResponse)
    			fmt.Println("job success")
    			break
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_FAILED {
    			log.Fatal("job fail", err)
    			return
    		}
    
    		time.Sleep(30 * time.Second)
    	}
    
    }
    

    Parameters:

    Parameter

    Description

    Type

    Required

    jobId

    Job ID returned in the service response.

    int32

    Yes

  • The following describes how the response is parsed.

    The service returns an AsyncJobResponse object with the following fields:

    Parameter

    Description

    Type

    RequestId

    Request ID.

    string

    Code

    Request status code indicating completion: OK or error.

    string

    Message

    Detailed request status. Returns success on success; otherwise, returns specific details.

    string

    Data

    Details of returned data.

    AsyncJobData

    Parsing the AsyncJobData.Job field (AsyncJobResult)

    Parameter

    Description

    Type

    State

    Verification result for each image.

    int32

    AppId

    Account AppId.

    string

    Message

    Detailed request status. Returns success on success; otherwise, returns specific details.

    string

    Result

    Model output.

    string

    After model training is complete, the Result field contains the following:

    Parameter

    Description

    cost_time

    Total training time consumed.

    states

    Verification result for each image.

    Detection result for each input image. Each image corresponds to a dictionary with three keys: url, message, and frontal. These represent the image URL, detection details, and whether the image is front-facing.

    model_id

    LoRA model name, identical to model_id from training

    LoRA model name from training, used as input for portrait creation

Portrait creation request

  • Solo portrait creation (client.AIGCApi.AigcImagesCreate)

    • Stable Diffusion 1.5 prediction

      package main
      
      import (
      	"encoding/base64"
      	"log"
      	"os"
      
      	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
      )
      
      func main() {
        // Get HOST, AppId, and Token from environment variables.
      	host := os.Getenv("Host")
      	appId := os.Getenv("AppId")
      	token := os.Getenv("Token")
      
      	client := sdk.NewClient(host, appId, token)
      
      	modelID := "xxxxxxxxxxxxxxx"
      
      	template_image := "https://template_case.png"
      
      	config := make(map[string]interface{}, 10)
      	config["lora_weights"] = 0.9
      	config["first_denoising_strength"] = 1
      	config["second_denoising_strength"] = 1
      	config["more_like_me"] = 1
      	config["crop_face_preprocess"] = false
      	config["apply_face_fusion_before"] = false
      	config["apply_face_fusion_after"] = false
      	config["color_shift_middle"] = false
      	config["color_shift_last"] = false
      	config["background_restore"] = true
      
      	response, err := client.AIGCApi.AigcImagesCreate(modelID, image, "", config)
      
      	if err != nil {
      		log.Fatal(err)
      	}
      
      	image_decode, _ := base64.StdEncoding.DecodeString(response.Data.Image)
      
      	f, err_2 := os.Create("test.jpg")
      	f.Write(image_decode)
      
      	if err_2 != nil {
      		log.Fatal(err)
      	}
      
      }
      

      Parameter

      Description

      Type

      Required

      modelID

      LoRA model name. Use the model-id obtained from training.

      string

      Yes

      template_image

      Template image URL

      string

      Yes

      config

      Model return configuration (default: nil)

      map[string]interface{}

      Yes

      Parameters in config

      Internal Parameter Name

      Description

      Type

      Required

      Default

      Valid values

      lora_weights

      LoRA strength.

      float

      No

      0.90

      0.5–1.0

      first_denoising_strength

      Strength of the first image reconstruction.

      float

      No

      0.45

      0.0–1.0

      second_denoising_strength

      Strength of the second image reconstruction.

      float

      No

      0.30

      0.0–1.0

      more_like_me

      That's more my speed.

      float

      No

      0.50

      0.0–1.0

      crop_face_preprocess

      Whether to crop the image before reconstruction. Recommended for large images.

      bool

      No

      True

      True, False

      apply_face_fusion_before

      Whether to perform the first portrait merging.

      bool

      No

      True

      True, False

      apply_face_fusion_after

      Whether to perform the second portrait merging.

      bool

      No

      True

      True, False

      color_shift_middle

      Whether to perform the first color correction.

      bool

      No

      True

      True, False

      color_shift_last

      Whether to perform the second color correction.

      bool

      No

      True

      True, False

      background_restore

      Whether to reconstruct the background.

      bool

      No

      False

      True, False

      skin_retouching_bool

      Whether to perform skin smoothing.

      When enabled, smooths and brightens skin, generally improving appearance but potentially causing overly pale skin. Disabling improves skin texture.

      bool

      No

      False

      True, False

      photo_enhancement_bool

      Whether to enhance the portrait.

      When enabled, performs portrait restoration or super resolution to improve image quality.

      bool

      No

      True

      True, False

      photo_enhancement_method

      Portrait enhancement method.

      photo_fix performs image restoration, which may cause some distortion but fixes unreasonable areas and may reduce skin texture.

      super_resolution only performs super resolution, preserving more of the original image.

      string

      No

      photo_fix

      photo_fix, super_resolution

      makeup_transfer

      Whether to perform makeup transfer.

      When enabled, transfers makeup to prevent overly plain images, but may reduce resemblance to the user.

      bool

      No

      False

      True, False

      makeup_transfer_ratio

      Strength of makeup transfer.

      Higher values increase makeup transfer proportion and resemblance to the template, but may reduce user resemblance.

      float

      No

      0.5

      0.0–1.0

      face_shape_match

      Whether to adapt face shape.

      When enabled, reduces control strength, making face shape and skin texture closer to the user.

      bool

      No

      False

      True, False

      ipa_control

      Whether to enable IP-Adapter control.

      When enabled, increases portrait similarity but makes results more sensitive to reference images.

      bool

      No

      False

      True, False

      ipa_control_only

      When enabled, allows prediction without training.

      Requires ipa_image_path when enabled.

      bool

      No

      False

      True, False

      ipa_image_path

      Reference portrait URL.

      Required when ipa_control_only is enabled.

      string

      No

      None

      Downloadable URL

      ipa_weight

      IP-Adapter control strength.

      Higher values increase user resemblance but may cause image distortion if too high.

      float

      No

      0.5

      0.0–1.0

      style_name

      Set the style for the generated output

      Realistic or Anime style.

      string

      No

      Realistic

      Realistic,

      Anime

      lcm_accelerate

      Controls the generation style and the use of LCM acceleration.

      bool

      No

      False

      True, False

      sharp_ratio

      Sharpening level. Appropriate values improve clarity.

      Excessive values cause image distortion.

      float

      No

      0.15

      0.0–1.0

      t2i_prompt

      Set this parameter to use text-to-image generation.

      If t2i_prompt is set, you do not need to provide a template URL.

      String

      No

      None

      N/A

    • SDXL prediction

      To use SDXL, contact your account manager to activate the service. Then, specify the model name.

      package main
      
      import (
      	"encoding/base64"
      	"log"
      	"os"
      
      	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
      )
      
      func main() {
        // Get HOST, AppId, and Token from environment variables.
      	host := os.Getenv("Host")
      	appId := os.Getenv("AppId")
      	token := os.Getenv("Token")
      
      	client := sdk.NewClient(host, appId, token)
      
      	modelID := "xxxxxxxxxxxx"
      
      	template_image := "https://template_case.png"
      
      	modelName := "create_xl"
      	config := make(map[string]interface{}, 10)
      	// config["lora_weights"] = 0.9
      	// config["first_denoising_strength"] = 1
      	// config["second_denoising_strength"] = 1
      	// config["more_like_me"] = 1
      	// config["crop_face_preprocess"] = false
      	// config["apply_face_fusion_before"] = false
      	// config["apply_face_fusion_after"] = false
      	// config["color_shift_middle"] = false
      	// config["color_shift_last"] = false
      	// config["background_restore"] = true
      
      	response, err := client.AIGCApi.AigcImagesCreate(modelID, image, modelName, config)
      
      	if err != nil {
      		log.Fatal(err)
      	}
      
      	image_decode, _ := base64.StdEncoding.DecodeString(response.Data.Image)
      
      	f, err_2 := os.Create("test.jpg")
      	f.Write(image_decode)
      
      	if err_2 != nil {
      		log.Fatal(err)
      	}
      
      }
      

      Parameter Name

      Type

      Description

      modelID

      string

      LoRA model name from training. Set to "" when using ipa_control_only mode

      template_image

      string

      The URL path for the template.

      Set to "t2i_generate" when using scene_lora or prompt generation.

      modelName

      string

      Model name. Set to create_xl for SDXL.

      config

      map[string]interface{}

      Model return configuration (default: None)

      Parameters in config

      Internal configuration parameter name

      Description

      Type

      Required

      Default

      Valid values

      lora_weights

      LoRA application strength.

      Higher values increase user resemblance but may cause image distortion if too high.

      float

      No

      0.90

      0.5–1.0

      first_diffusion_steps

      Steps for first diffusion.

      Changing this value is not recommended. A value that is too low will cause image aliasing.

      int

      No

      50

      20–50

      first_denoising_strength

      Strength of the first image reconstruction.

      Face reconstruction strength. Higher values increase reconstruction and user resemblance, but excessive values cause image inconsistency.

      float

      No

      0.45

      0.0–1.0

      second_diffusion_steps

      Steps for second diffusion.

      Do not modify. Too few steps cause image distortion.

      int

      No

      30

      20–50

      second_denoising_strength

      Strength of the second image reconstruction.

      Facial edge reconstruction strength. Excessive values cause image inconsistency.

      float

      No

      0.30

      0.0–1.0

      more_like_me

      That's more my speed.

      Portrait merging ratio. Higher values increase resemblance to the subject, but excessive values reduce realism.

      float

      No

      0.60

      0.0–1.0

      crop_face_preprocess

      Whether to crop the image before reconstruction. Recommended for large images.

      Do not adjust.

      bool

      No

      True

      True, False

      apply_face_fusion_before

      Whether to perform the first portrait merging.

      When enabled, performs portrait merging. Disabling reduces similarity.

      bool

      No

      True

      True, False

      apply_face_fusion_after

      Whether to perform the second portrait merging.

      When enabled, performs portrait merging. Disabling reduces similarity.

      bool

      No

      True

      True, False

      color_shift_middle

      Whether to perform the first color correction.

      When enabled, corrects colors to match template skin tone. Disabling may cause color bias.

      bool

      No

      True

      True, False

      color_shift_last

      Whether to perform the second color correction.

      When enabled, corrects colors to match template skin tone. Disabling may cause color bias.

      bool

      No

      True

      True, False

      background_restore

      Whether to reconstruct the background.

      When enabled, reconstructs background for a more natural look, but changes the background and increases processing time.

      bool

      No

      False

      True, False

      skin_retouching_bool

      Whether to perform skin smoothing.

      When enabled, smooths and brightens skin, generally improving appearance but potentially causing overly pale skin. Disabling improves skin texture.

      bool

      No

      False

      True, False

      photo_enhancement_bool

      Whether to enhance the portrait.

      When enabled, performs portrait restoration or super resolution to improve image quality.

      bool

      No

      True

      True, False

      photo_enhancement_method

      Portrait enhancement method:

      photo_fix performs image restoration, which may cause some distortion but fixes unreasonable areas and may reduce skin texture.

      super_resolution only performs super resolution, preserving more of the original image.

      String

      No

      photo_fix

      photo_fix, super_resolution

      makeup_transfer

      Whether to perform makeup transfer.

      When enabled, transfers makeup to prevent overly plain images, but may reduce user resemblance.

      bool

      No

      False

      True, False

      makeup_transfer_ratio

      Strength of makeup transfer.

      Higher values increase makeup transfer proportion and resemblance to the template, but may reduce user resemblance.

      float

      No

      0.5

      0.0–1.0

      ipa_control

      Whether to enable IP-Adapter control.

      When enabled, increases portrait similarity but makes results more sensitive to reference images.

      bool

      No

      False

      True, False

      ipa_control_only

      When enabled, allows prediction without training.

      Requires ipa_image_path when enabled.

      bool

      No

      False

      True, False

      ipa_image_path

      Reference portrait URL.

      Required when ipa_control_only is enabled.

      String

      No

      None

      Downloadable URL

      ipa_weight

      IP-Adapter control strength.

      Higher values increase user resemblance but may cause image distortion if too high.

      float

      No

      0.5

      0.0–1.0

      lcm_accelerate

      Specifies what generation style to use and whether to use LCM acceleration.

      bool

      No

      False

      True, False

      sharp_ratio

      Sharpening level. Appropriate values improve clarity.

      Excessive values cause image distortion.

      float

      No

      0.15

      0.0–1.0

      scene_id

      Set this parameter to use scene lora.

      scene_id comes from training. The model_id returned during SDXL scene LoRA training is the scene_id.

      String

      No

      None

      N/A

      t2i_prompt

      Set this parameter to use text-to-image generation.

      If t2i_prompt is set, you do not need to provide a template URL.

      String

      No

      None

      N/A

  • Group portrait creation (client.AIGCApi.AigcImagesCreateByMultiModelIds)

    package main
    
    import (
    	"encoding/base64"
    	"log"
    	"os"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
      // Get HOST, AppId, and Token from environment variables.
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    
    	modelIDs := []string{"xxxxxx", "xxxxxx"}
    
    	template_image := "https://template_case.png"
    
    	config := make(map[string]interface{}, 10)
    	config["lora_weights"] = 0.9
    	config["first_denoising_strength"] = 1
    	config["second_denoising_strength"] = 1
    	config["more_like_me"] = 1
    	config["crop_face_preprocess"] = false
    	config["apply_face_fusion_before"] = false
    	config["apply_face_fusion_after"] = false
    	config["color_shift_middle"] = false
    	config["color_shift_last"] = false
    	config["background_restore"] = true
    
    	response, err := client.AIGCApi.AigcImagesCreateByMultiModelIds(modelIDs, image, "", config)
    
    	image_decode, _ := base64.StdEncoding.DecodeString(response.Data.Image)
    
    	f, err := os.Create("test.jpg")
    	f.Write(image_decode)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    
    }
    

    Parameter Name

    Description

    Type

    Required

    modelIds

    model_id values of all LoRA models used for image generation.

    []string

    Yes

    template_image

    The path to the template.

    string

    Yes

    config

    Model return configuration (default: nil)

    map[string]interface{}

    Yes

  • Response parsing:

    The service returns an AIGCImageCreateResponse object with the following fields:

    Parameter Name

    Description

    Type

    RequestId

    Request ID.

    string

    Code

    Request status code indicating completion: OK or error.

    string

    Message

    Detailed request status. Returns success on success; otherwise, returns specific details.

    string

    Data

    Details of returned data.

    AIGCImageCreateData

    Fields of the AIGCImageCreateData data type:

    Parameter

    Description

    Type

    CostTime

    Time spent generating the image.

    Float

    Image

    Base64-encoded image.

    String

  • Error code descriptions

    1. Service request error codes:

      HTTP status code

      code

      message

      Description

      400

      PARAMETER_ERROR

      not found appid

      Invalid AppId.

      400

      EXCEEDED_QUOTA_ERROR

      exceeded quota

      Account call quota exhausted.

      401

      PARAMETER_ERROR

      sign error

      Invalid token.

      404

      PARAMETER_ERROR

      model not found

      Requested model service not deployed.

    2. Result query error codes:

      HTTP status code

      code

      message

      Description

      462

      error

      Invalid input data. Please check the input dict.

      Input data parsing error.

      462

      error

      Image not provided. Please check the template_image.

      No template image provided for portrait creation.

      462

      error

      Prompts get error. Please check the model_id.

      Check the format of the provided model_id.

      462

      error

      Roop image decode error. Please check the user's lora is trained or not.

      Roop image does not exist. Check if the model is trained.

      462

      error

      Template image decode error. Provide a new template

      Template image decode error. Provide a new template

      462

      error

      There is not face in template. Please Give a new template.

      No face found in template image. Provide a new template.

      462

      error

      Template image process error. Please Give a new template.

      Template image preprocessing error. Provide a new template.

      469

      error

      First Face Fusion Error, Can't get face in template image.

      First portrait merging failed.

      469

      error

      First Stable Diffusion Process error. Check the webui status.

      First Stable Diffusion processing failed.

      469

      error

      Second Face Fusion Error, Can't get face in template image.

      Second portrait merging failed.

      469

      error

      Second Stable Diffusion Process error. Check the webui status.

      Second Stable Diffusion processing failed.

      469

      error

      Please confirm if the number of faces in the template corresponds to the user ID.

      Verify that the number of user IDs matches the number of faces.

      469

      error

      Third Stable Diffusion Process error. Check the webui status.

      Background processing failed. Replace the template.

      500

      error

      Face id image decode error. Pleace check the user's lora is trained or not.

      Face ID image decoding error. Check if the model is trained.

End-to-end workflow sample code

  • Standard workflow (SD15)

    package main
    
    import (
    	"encoding/base64"
    	"fmt"
    	"log"
    	"os"
    	"time"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    	images := []string{"https://train/0.jpg","https://train/1.jpg","https://train/2.jpg","https://train/3.jpg"}
    		
    	trainresponse, err := client.AIGCApi.AigcImagesTrain(images, "", nil)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	jobId := trainresponse.Data.JobId
    	modelId := trainresponse.Data.ModelId
    	fmt.Println(jobId)
    
    	jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    	fmt.Println(jobResponse.Data.Job.Message)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	for {
    		jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    		fmt.Println(jobResponse.Data.Job.Result)
    		if err != nil {
    			log.Fatal("get job fail", err)
    		}
    
    		if jobResponse.Data.Job.State == sdk.JOB_STATE_WAIT {
    			fmt.Println("job running")
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_SUCCESS { // job success
    			fmt.Println(jobResponse)
    			fmt.Println("job success")
    			break
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_FAILED {
    			log.Fatal("job fail", err)
    			return
    		}
    
    		time.Sleep(30 * time.Second)
    
    	}
    	fmt.Println(modelId)
    
    	template_image := "https://template_case.png"
    
    	config := make(map[string]interface{}, 10)
    	config["lora_weights"] = 0.9
    	config["first_denoising_strength"] = 1
    	config["second_denoising_strength"] = 1
    	config["more_like_me"] = 1
    	config["crop_face_preprocess"] = false
    	config["apply_face_fusion_before"] = false
    	config["apply_face_fusion_after"] = false
    	config["color_shift_middle"] = false
    	config["color_shift_last"] = false
    	config["background_restore"] = true
    
    	createresponse, err := client.AIGCApi.AigcImagesCreate(modelId, template_image, "", config)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	image_decode, _ := base64.StdEncoding.DecodeString(createresponse.Data.Image)
    
    	f, err := os.Create("test.jpg")
    	f.Write(image_decode)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    

    Parameter

    Description

    Type

    Required

    images

    List of training image URLs.

    []string

    Yes

    template_image

    The template's URL path.

    string

    Yes

    config

    Model return configuration. Default: nil.

    map[string]interface{}

    Yes

  • Standard workflow (SDXL)

    package main
    
    import (
    	"encoding/base64"
    	"fmt"
    	"log"
    	"os"
    	"time"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    	images := []string{
                "https://xxx/0.jpg",
                "https://xxx/1.jpg",
                "https://xxx/2.jpg"}
                         
    	trainresponse, err := client.AIGCApi.AigcImagesTrain(images, "train_xl", nil)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	jobId := trainresponse.Data.JobId
    	modelId := trainresponse.Data.ModelId
    	fmt.Println(jobId)
    
    	jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    	fmt.Println(jobResponse.Data.Job.Message)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	for {
    		jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    		fmt.Println(jobResponse.Data.Job.Result)
    		if err != nil {
    			log.Fatal("get job fail", err)
    		}
    
    		if jobResponse.Data.Job.State == sdk.JOB_STATE_WAIT {
    			fmt.Println("job running")
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_SUCCESS { // job success
    			fmt.Println(jobResponse)
    			fmt.Println("job success")
    			break
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_FAILED {
    			log.Fatal("job fail", err)
    			return
    		}
    
    		time.Sleep(30 * time.Second)
    
    	}
    	fmt.Println(modelId)
    
    	template_image = "https://demo.jpg"
    
    	config := make(map[string]interface{}, 10)
    
    	createresponse, err := client.AIGCApi.AigcImagesCreate(modelId, template_image, "create_xl", config)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	image_decode, _ := base64.StdEncoding.DecodeString(createresponse.Data.Image)
    
    	f, err := os.Create("test.jpg")
    	f.Write(image_decode)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    

    Parameter Name

    Description

    Type

    Required

    images

    List of training image URLs.

    []string

    Yes

    template_image

    Template URL path

    string

    Yes

    config

    Model return configuration. Default: nil.

    map[string]interface{}

    Yes

  • Creating an ingest endpoint from a single reference graph without training

    package main
    
    import (
    	"encoding/base64"
    	"log"
    	"os"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    
    	template_image = "https://demo.jpg"
      ref_image = "https://reference.jpg"
      
    	config := make(map[string]interface{}, 10)
    	config["ipa_control_only"] = true
    	config["ipa_weight"] = 0.6
    	config["ipa_image_path"] = ref_image
    
    	createresponse, err := client.AIGCApi.AigcImagesCreate("", template_image, "", config)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	image_decode, _ := base64.StdEncoding.DecodeString(createresponse.Data.Image)
    
    	f, err := os.Create("test.jpg")
    	f.Write(image_decode)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    

    Parameter name

    Description

    Type

    Required

    template_image

    The template's URL path.

    string

    Yes

    ref_image

    Reference image URL

    string

    Yes

    config

    Model return configuration. Default: nil.

    map[string]interface{}

    Yes

  • Generate a template creation workflow from prompts

    package main
    
    import (
    	"encoding/base64"
    	"fmt"
    	"log"
    	"os"
    	"time"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    	images := []string{"https://xxx/0.jpg",
          							 "https://xxx/1.jpg",
                         "https://xxx/2.jpg"}
    	trainresponse, err := client.AIGCApi.AigcImagesTrain(images, "", nil)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	jobId := trainresponse.Data.JobId
    	modelId := trainresponse.Data.ModelId
    	fmt.Println(jobId)
    
    	jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    	fmt.Println(jobResponse.Data.Job.Message)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	for {
    		jobResponse, err := client.JobApi.GetAsyncJobWithId(jobId)
    		fmt.Println(jobResponse.Data.Job.Result)
    		if err != nil {
    			log.Fatal("get job fail", err)
    		}
    
    		if jobResponse.Data.Job.State == sdk.JOB_STATE_WAIT {
    			fmt.Println("job running")
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_SUCCESS { // job success
    			fmt.Println(jobResponse)
    			fmt.Println("job success")
    			break
    		} else if jobResponse.Data.Job.State == sdk.JOB_STATE_FAILED {
    			log.Fatal("job fail", err)
    			return
    		}
    
    		time.Sleep(30 * time.Second)
    
    	}
    	fmt.Println(modelId)
    
    	template_image = "https://demo.jpg"
    
    	t2i_prompt := "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, enormous filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup"
    
    	config := make(map[string]interface{}, 10)
    	config["t2i_prompt"] = t2i_prompt
    
    	createresponse, err := client.AIGCApi.AigcImagesCreate(modelId, template_image, "", config)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	image_decode, _ := base64.StdEncoding.DecodeString(createresponse.Data.Image)
    
    	f, err := os.Create("test.jpg")
    	f.Write(image_decode)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    

    Parameter Name

    Description

    Type

    Required

    images

    List of images for LoRA training.

    []string

    Yes

    template_image

    The URL path for the template.

    string

    Yes

    t2i_prompt

    Prompt

    string

    Yes

    config

    Model return configuration. Default: nil.

    map[string]interface{}

    Yes

  • Generate a template using a prompt and a single reference image without a template or training

    package main
    
    import (
    	"encoding/base64"
    	"log"
    	"os"
    
    	sdk "github.com/aliyun/aliyun-pai-aiservice-go-sdk"
    )
    
    func main() {
    	host := os.Getenv("Host")
    	appId := os.Getenv("AppId")
    	token := os.Getenv("Token")
    
    	client := sdk.NewClient(host, appId, token)
    
    	template_image = "https://demo.jpg"
      ref_image = "https://reference.jpg"
      
    	t2i_prompt := "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, enormous filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup"
    
    	config := make(map[string]interface{}, 10)
    	config["ipa_control_only"] = true
    	config["ipa_weight"] = 0.6
    	config["ipa_image_path"] = ref_image
    	config["t2i_prompt"] = t2i_prompt
    
    	createresponse, err := client.AIGCApi.AigcImagesCreate("", template_image, "", config)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	image_decode, _ := base64.StdEncoding.DecodeString(createresponse.Data.Image)
    
    	f, err := os.Create("test.jpg")
    	f.Write(image_decode)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    

    Parameter

    Description

    Type

    Required

    ref_image

    Reference image URL path.

    string

    Yes

    template_image

    Template path

    string

    Yes

    t2i_prompt

    Prompt.

    string

    Yes

    config

    Model return configuration. Default: nil.

    map[string]interface{}

    Yes

References

For more information, see the Go SDK GitHub repository.