AI portrait generation API details

更新时间:
复制 MD 格式

Important

This document applies only to the China (Beijing) region.

AI portrait generation

Note

Supported realm/task: aigc/facechain AI portrait generation

AI Portrait 2.0 supports two modes: the LoRA model training mode and the training-free mode.

1) LoRA model training mode: This mode uses a pre-trained LoRA model of a character's likeness. You can then use the portrait generation model to create high-fidelity portraits of that character. This mode supports multiple preset styles, such as ID photos, business portraits, retro, and summer sports. You can also upload custom style templates to generate personalized AI portraits.

2) Training-free mode (Recommended): You can upload a set of user photos (at least one clear, front-facing photo) and a custom style template. The portrait generation model then instantly creates an AI portrait without any training. This mode only supports generating portraits using uploaded custom style templates.

LoRA model training mode details:

  • Flowchart for the LoRA model training mode:

image.png

In the LoRA model training mode, AI portrait generation uses the image generation capabilities of a diffusion model and combines them with LoRA training to merge a person's likeness with a specific style. A series of post-processing steps are then applied to create portraits that are realistic, aesthetically pleasing, and closely resemble the subject. This method produces highly personalized, high-fidelity, and high-quality portraits.

The following images show examples of this feature:

  • Input image

image.png

  • Generated result (Business portrait)

image.png

  • Preset style template

image.png

  • Custom template:

  • Input image

image.png

  • Custom template

image.jpeg

  • Generated result

image.jpeg

Training-free mode details:

  • Flowchart for the training-free mode:

image.png

The training-free mode uses powerful, built-in pre-trained foundation models for AI portraits. This allows the diffusion model to generate images instantly without training. A series of post-processing steps are also applied to create portraits that are realistic, aesthetically pleasing, and closely resemble the subject. This method produces highly personalized, high-quality, and diverse portraits with high generation speeds.

The following images show examples of this feature:

  • Input image

image.jpeg

  • Custom template

image.jpeg

  • Generated result

image.jpeg

Scenarios

  • Professional ID photo creation: You can instantly train an ID photo style for a user to create high-quality, standardized professional ID photos for various scenarios, such as corporate recruitment and resumes. This saves time, effort, and cost.

  • AI portrait studio application: You can build an intelligent portrait studio application to provide users with a convenient, efficient, and highly personalized online photography experience. This lets users take high-quality, diverse personal portraits that are comparable to professional photos, anytime and anywhere.

  • Global travel portrait generation: You can create an innovative digital application for generating travel portraits. This gives users the experience of having professional travel photos taken around the world. Users can obtain beautiful personal portraits in front of global landscapes and famous attractions without needing to travel.

  • Commercial portrait creation: You can generate commercial portraits in batches. This is ideal for business figures, models, influencers, or corporate executives who need high-quality portraits for social media, promotional materials, magazine covers, and other commercial activities.

Features and advantages

  • High-fidelity portrait creation: The face is naturally fused into the portrait. The generated portrait has a consistent facial expression, detailed features, and skin tone. It also features high definition and accurate color reproduction, resulting in superior image quality.

  • Personalized style customization: This feature supports a high degree of customization with different template styles, including various scenes and shooting styles.

  • Efficient character design: Compared to traditional photography, AIGC technology eliminates the need for an actual photoshoot, saving time and labor costs. It can generate many portraits in different styles in a short time, meeting the demand from consumer clients for diverse and rapid responses.

  • Face quality assessment for portrait training: The service assesses whether the uploaded face images meet the standards required for portrait generation fine-tuning. It performs a multi-dimensional quality check on the number of faces, size, angle, lighting, and definition.

  • Stable and easy-to-use platform service: The service provides stable portrait generation responses under high concurrency and heavy traffic, with a 99.99% reliability guarantee. It offers simple training and inference APIs that are easy to call, integrate, and highly compatible.

Model overview

Model name

Model description

facechain-generation

Based on a character likeness that has already been trained, you can use the portrait generation model to create portraits of that character. It supports multiple preset styles, such as ID photos and business portraits.

Input limits

Limits for single-person photos:

  • Image format: JPEG, JPG, PNG.

  • Image size: No larger than 3 MB.

  • Image resolution: Greater than 256 × 256 pixels and less than 2048 × 2048 pixels. The face in the image must be at least 128 × 128 pixels.

  • The URL cannot contain Chinese characters.

  • The image must be a clear, front-facing photo of a single person. The face angle cannot exceed 15 degrees.

  • You must provide at least 1 and up to 5 input images. The images must first be verified using the face detection API (facechain-facedetect).

Limits for custom templates:

  • Image format: JPEG, JPG, PNG.

  • Image size: No larger than 5 MB.

  • Image resolution: Greater than 512 × 512 pixels and less than 1680 × 1260 pixels.

  • The URL cannot contain Chinese characters.

  • The template must be a clear, high-quality image of a single person. The face must not be occluded or blurred.

HTTP invocation interface

Feature description

This model requires a relatively long time for algorithm invocation. Therefore, the API uses asynchronous invocation to submit tasks. After you submit a job through the task interface, the system returns a job ID. You can then use the asynchronous job query interface to check the task status and retrieve the results after the job completes.

Prerequisites

  • You have activated the service and obtained an API key. For more information, see Get and configure an API key.

  • You have completed model training for a custom likeness using the character training API and obtained the corresponding resource_id. For more information, see Character training API details.

Note

API limits: For a single account (including the Alibaba Cloud account and its RAM users), the queries per second (QPS) limit for submitting tasks is 2, and the concurrent task limit is 1.

Job submission API call

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/album/gen_potrait

Replace {WorkspaceId} with your actual workspace ID.

Request parameters

Parameter passing methods

Field

Type

Required

Description

Example

Header

Content-Type

String

Yes

Request type: application/json

application/json

Authorization

String

Yes

Your API key. Example: Bearer d1**2a

Bearer d1**2a

X-DashScope-Async

String

Yes

Set to enable to submit the job asynchronously.

enable

Body

model

String

Yes

The model to call. Set this to facechain-generation.

facechain-generation

resources[list]

Array

No

Specifies the data for the LoRA layer obtained from model customization. This parameter is required for non-training-free generation.

For training-free generation, you do not need to set this parameter because it is ignored.

"resources": [

{

"resource_id": "realistic_v1_12345",

"resource_type": "facelora"

}

]

resources[0].resource_type

String

No

The data type for model customization, which is `facelora` in this case. This parameter is required for generation that is not training-free.

This parameter is not applicable to training-free generation.

resources[0].resource_id

String

No

The data ID of the LoRA layer obtained from model customization. Obtain this ID from the finetuned_output of a successful model customization task. Example: facechain-png-ft-202308291948-edc2. This parameter is required for generation that is not training-free.

For training-free generation, you do not need to specify this parameter because any input is ignored.

parameters.style

String

No

You can select a preset style, the custom template mode, or the training-free custom template mode for the output image.

Preset styles:

The following preset styles are supported:

f_idcard_male (Male ID photo) f_business_male (Male business portrait) f_idcard_female (Female ID photo)

f_business_female (Female business portrait)

m_springflower_female (Spring garden)

f_summersport_female (Summer sports)

f_autumnleaf_female (Autumn impression)

m_winterchinese_female (Winter Chinese style)

f_hongkongvintage_female (Hong Kong retro)

f_lightportray_female (Light portrait)

Custom template portrait generation:

portrait_url_template

Training-free custom template portrait generation:

train_free_portrait_url_template

"style": "f_business_female"

parameters.size

String

No

The resolution of the generated image. Currently, only '768*1024' is supported.

This parameter is not required for custom template modes.

"parameters": {

"size": "768*1024",

"n": 4,

"skin_retouch": true

}

parameters.n

Integer

No

The number of images to generate. Valid values: 1 to 4. Default value: 4.

parameters.skin_retouch

Bool

No

Specifies whether to automatically apply retouching to the input user image during training-free portrait generation. The default value is 'true', which enables automatic retouching. Set it to 'false' to disable automatic retouching. You can perform your own pre-processing and post-processing for retouching.

input.template_url

String

No

When parameters.style is set to "portrait_url_template" or "train_free_portrait_url_template", you must upload a custom template to generate the portrait. This parameter is required in these cases. Pass the URL of the custom template.

template_url: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left3.png"

input.user_urls

Array

No

When parameters.style is set to "train_free_portrait_url_template", it indicates training-free portrait generation with a custom template. This parameter is required in this case. Pass the URLs of a set of front-facing photos of a single user. Provide at least 1 and up to 5 images that have been verified by the face detection API (facechain-facedetect).

user_urls:[ "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png"]

Response parameters

Field

Type

Description

Example

output.task_id

String

The ID of the submitted asynchronous job. You must use the asynchronous task query interface to get the actual job results.

xxxxxxxxx

output.task_status

String

The status of the job after submission.

"PENDING"

request_id

String

The unique ID of the request.

7574ee8f-38a3-4b1e-9280-11c33ab46e51

Request examples

The following example shows how to call this model using a cURL command.

Note

Replace <your-dashscope-api-key> with your API key for the code to run correctly.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/album/gen_potrait' \
--header 'X-DashScope-Async: enable' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--data '{
"model": "facechain-generation",
"parameters": {
"style": "f_idcard_female", 
"size": "768*1024",
"n":4
},
"resources": [
{
"resource_id": "women_model",
"resource_type": "facelora"
}
]
}'

The following example shows how to call this model to generate a portrait with a custom template using a cURL command.

Note

Replace <your-dashscope-api-key> with your API key and replace <template_pic_url> with the URL of your custom template image for the code to run correctly.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/album/gen_potrait' \
--header 'X-DashScope-Async: enable' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--data '{
"model": "facechain-generation",
"parameters": {
"style": "portrait_url_template", 
"n":1
},
"input": 
{
"template_url": "<template_pic_url>"
},
"resources": [
{
"resource_id": "women_model",
"resource_type": "facelora"
}
]
}'

The following example shows how to call this model to generate a training-free portrait with a custom template using a cURL command.

Note

Replace <your-dashscope-api-key> with your API key, replace <template_pic_url> with the URL of your custom template image, and replace <user_pic_url> with the URL of the user's front-facing photo for the code to run correctly.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/album/gen_potrait' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'X-DashScope-Async: enable' \
--header 'Content-Type: application/json' \
--data '{
    "model": "facechain-generation",
    "parameters":
    {
        "style": "train_free_portrait_url_template",
        "n": 1
    },
    "input":
    {
      "template_url": "<template_pic_url>",
      "user_urls": ["<user_pic_url>"]
    }
}'

Response example

{
  "request_id": "0b6a411a-56e6-9028-84eb-6852183248d8",
  "output": {
    "task_id": "7eb1032e-09a1-4df5-96ed-14091859ad57",
    "task_status": "SUCCEEDED",
    "submit_time": "2025-08-15 10:20:22.629",
    "scheduled_time": "2025-08-15 10:20:22.655",
    "end_time": "2025-08-15 10:20:50.540",
    "results": [
      {
        "url": "https://example.com/image1.jpg"
      },
      {
        "url": "https://example.com/image2.jpg"
      },
      {
        "url": "https://example.com/image3.jpg"
      },
      {
        "url": "https://example.com/image4.jpg"
      }
    ],
    "task_metrics": {
      "TOTAL": 4,
      "SUCCEEDED": 4,
      "FAILED": 0
    }
  },
  "usage": {
    "image_count": 4
  }
}

Error response example

If an error occurs when you submit a job request, the output includes the `code` and `message` fields to indicate the cause of the error.

{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"fb53c4ec-1c12-4fc4-a580-cdb7c3261fc1"
}

Job status query and result retrieval interface

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Replace {WorkspaceId} with your actual workspace ID.

Request parameters

Parameter Passing

Field

Type

Required

Description

Example

URL Path

task_id

String

Yes

The task_id of the job to query.

13b1848b-5493-4c0e-8c44-68d038b492af

Header

Authorization

String

Yes

Your API key. Example: Bearer d1**2a

Bearer d1**2a

Response parameters

Field

Type

Description

Example

output.task_id

String

The ID of the asynchronous job for this request. You must use the asynchronous task query interface to get the actual job results.

13b1848b-5493-4c0e-8c44-68d038b492af

output.task_status

String

The status of the queried job.

Task status:

PENDING: The task is in the queue.

RUNNING: The task is being processed.

Succeeded

Failed

UNKNOWN: The job does not exist or its status is unknown.

output.result_url

String

If the job is successful, this field contains the URL of the generated image. You can download the image from this URL within 24 hours.

The output image resolution is 768 × 1024.

"result_url": "http://oss.aliyuncs.com/xxx/abc.jpg"

usage.image_count

Int

The number of images generated for this request.

"image_count": 1

request_id

String

The unique ID of the request.

7574ee8f-38a3-4b1e-9280-11c33ab46e51

Request example

The following example shows how to call this model using a cURL command.

Note

Replace <your-dashscope-api-key> with your API key for the code to run correctly.

curl -X GET \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-af6e-a0c6a421c010

Response example (job running)

After a job is submitted, it is placed in a queue. Once it is scheduled, its status changes to RUNNING. The `task_metrics` field provides the status of the specific batch.

{
    "request_id":"e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output":{
        "task_id":"86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status":"RUNNING",
        "task_metrics":{
            "TOTAL":1,
            "SUCCEEDED":1,
            "FAILED":0
        }
    }
}

Response example (job succeeded)

If the job completes successfully, querying the job status again returns both the status and the job results. For this model, the job status is retained for 24 hours after completion for you to query at any time. After 24 hours, the job and its results are purged from the system. The generated result is an image URL. For security reasons, this URL is also valid for only 24 hours. You must download or save the image as needed after you retrieve the job results.

{
  "request_id": "<your request id>",
  "output": {
    "task_id": "<your task id>",
    "task_status": "SUCCEEDED",
    "submit_time": "xxx",
    "scheduled_time": "xxx",
    "end_time": "xxx",
    "results": [
      {"url": "http://oss.aliyuncs.com/xxx/abc1.jpg"},
      {"url": "http://oss.aliyuncs.com/xxx/abc2.jpg"},
      {"url": "http://oss.aliyuncs.com/xxx/abc3.jpg"},
      {"url": "http://oss.aliyuncs.com/xxx/abc4.jpg"}
    ],
    "task_metrics": {
      "TOTAL": 4,
      "SUCCEEDED": 4,
      "FAILED": 0
    }
  },
  "usage": {
    "image_count": 4
  }
}

Response example (job failed)

If a job fails for any reason, its status is set to FAILED. The `code` and `message` fields indicate the cause of the error.

{
  "request_id": "<your request id>",
  "output": {
    "task_id": "<your task id>",
    "task_status": "FAILED",
    "submit_time": "xxx",
    "scheduled_time": "xxx",
    "end_time": "xxx",
    "code": "InvalidImageResolution",
    "message": "The input image resolution is too large or small"
  },
  "usage": {
    "image_num": 0
  }
}

Status codes

For general status codes of the foundation model service platform, see Error messages.

This model also has the following specific error codes:

HTTP return code*

Error code (code)

Error message (message)

Description

400

InvalidParameter

The request is missing required parameters or the parameters are out of the specified range, please check the parameters that you send

Required API call parameters are missing or out of range.

400

InvalidURL

The request URL is invalid, make sure the url is correct and is an image

The input URL is invalid. Make sure the URL is correct.

400

InvalidImageResolution

The input image resolution is too large or small

The input image resolution is too large or too small.

500

InternalError:Algo

An internal error occurs during computation, please try this model later

An internal algorithm error occurred. Try again later.

500

InternalError:Algo

Inference error: Inference error

Check if the input image file is corrupted or check the quality of the person's image (it must contain a complete and clear face).

FAQ

Why do I receive the error "code": "InternalError.Algo", "message": "Inference error: Inference error" when calling the AI portrait API?

  • Suggestion 1: Check whether the input image file is corrupted.

  • Suggestion 2: Check the quality of the input image. It must contain a complete and clear face.