生成文本建议

Text Suggestions API 利用 Product Studio API 的生成式 AI 工具来生成和优化商品名和说明。您可以使用它来提高客户互动度和转化率,并简化管理和更新商品信息的过程。Product Studio API 的功能可以帮助您优化零售表现。

您可以使用该 API 生成哪些内容?

Text Suggestions API 可帮助您执行以下操作:

  • 根据您的产品图片和/或商品属性生成建议的商品名和说明。
  • 为您的商品生成经过搜索引擎优化的商品名
  • 为您的商品生成自定义格式的商品名
  • 从商品 Feed 中生成商品说明

您还可以为说明指定语气,并在所有商品详情中保持一致。

快速入门

GenerateProductTextSuggestions 方法可以使用您的商品信息生成或优化商品名和说明。

该 API 接受以下内容:

  • 商品属性(JSON 字典): 包含商品 属性的 JSON 对象(例如 {"title": "White Tee", "brand": "MyBrand", "size": "XL"}
  • 产品图片: 指向产品图片的 URI(例如 {"uri": "https://my-store.com/img/1.png"}
  • 商品名格式设置选项:用于自定义商品名生成的参数, 包括:
    • attribute_separator:指定属性之间的分隔符。
    • target_language:设置输出语言。
    • attribute_order:定义生成的商品名中属性的顺序。
  • 数据标签示例:查看如何根据说明生成商品名 的示例
  • 工作流 ID (output_spec.workflow_id)workflow_id 对象中的 output_spec 字段决定了文本生成的类型:
    • title:生成或优化商品名。
    • description:生成或优化商品说明。
    • tide:同时生成或优化商品名和说明。

示例

以下示例展示了如何使用该 API 根据不同的商品数据输入生成或优化商品名、说明或两者。我们还介绍了常见 错误和问题及其解决方案。

优化商品名生成

该示例展示了如何生成最佳商品名。

请求

请求正文包含用于优化商品名的商品信息。 以下是请求结构的示例:

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "title": "Nike Mens shoes",
         "description": "Give strength to your step with the Nike Air Zoom Pegasus 38 shoe for Men with shoe size 12. Ensuring the fit is loved by the runners. This shoes comes in Blue color.",
         "brand": "Nike"
      }
   },
   "output_spec": {
      "workflow_id": "title"
   }
}

响应

您可能会看到如下所示的响应

{
  "title": {
    "text": "Nike Mens shoes Air Zoom Pegasus 38 Running Shoes, Blue, Size 12"
  },
  "metadata": {
    "metadata": {
      "attributes": {
        "color": "Blue",
        "size": "12",
        "product": "Running shoes",
        "model": "Air Zoom Pegasus 38"
      },
    }
  }
}

仅根据图片生成商品名

该示例展示了如何提供产品图片并生成最佳商品名。

请求

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_image":{
         "uri": "https://cdn.shopify.com/s/files/1/0653/5879/0892/products/1672082339438_550x825.jpg?v=1672082415"
      }
   },
   "output_spec": {
      "workflow_id": "title",
      "attribute_separator": "-"
   }
}

响应

{
  "title": {
    "text": "Rustic Ceramic & Leather Leaves Necklace"
  },
  "metadata": {
    "metadata": {
      "attributes": {
        "material": "Rustic Ceramic & Leather",
        "pattern": "Leaves",
        "product": "Necklace"
      },
    }
  }
}

根据说明生成商品名

该示例展示了如何提供商品说明并生成最佳商品名。

请求

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "description": "selling size 12 nike dunks. oh they are red by the way!"
      }
   },
   "output_spec": {
      "workflow_id": "title",
   }
}

响应

{
  "title": {
    "text": "Nike Dunks Red Size 12"
  },
  "metadata": {
    "metadata": {
      "attributes": {
        "brand": "Nike",
        "color": "Red",
        "size": "12",
        "product": "Dunks"
      },
    }
  }
}

根据商品名和说明优化商品名(附带自定义示例)

在此示例中,我们明确标记了希望 AI 识别的商品属性以及输出中属性的顺序。

请求

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "title": "Volumizing & Lengthening Mascara - Dark Brown",
         "description": "This high-impact mascara delivers both voluptuous volume and dramatic length without clumping or smudging.",
         "brand": "Luxe Beauty"
      }
   },
   "output_spec": {
      "workflow_id": "title"
   }
   "title_examples": [
    {
      "product_info": {
        "title": "Lash Paradise Volumizing & Lengthening Mascara - Waterproof - Blackest Black",
        "colour": "Black"
      },
      "title_format": "product",
      "category": "mascara",
      "final_product_info": {
        "product": "Mascara",
        "brand": "Lash Paradise",
        "mascara_type": "Volumizing & Lengthening",
        "colour": "Blackest Black",
        "waterproof": "Waterproof",
      }
    },
    {
      "product_info": {
        "title": "Hypnose Drama Instant Full Body Volume Mascara - Black",
        "colour": "Black"
      },
      "title_format": "product",
      "category": "mascara",
      "final_product_info": {
        "product": "Mascara",
        "brand": "Hypnose",
        "sub_brand": "Drama",
        "mascara_type": "Full Body Volume",
        "colour": "Black",
        "eye_lash_type": "All lash types"
      }
    }
  ]
}

响应

{
  "title": {
    "text": "Luxe Beauty Dark Brown Volumizing & Lengthening Mascara"
  },
  "metadata": {
    "metadata": {
      "attributes": {
        "brand": "Luxe Beauty",
        "colour": "Dark Brown",
        "mascara_type": "Volumizing & Lengthening",
        "product": "Mascara"
      },
    }
  }
}

根据商品名生成说明

该示例展示了如何提供商品名并要求 API 生成相应的商品说明。

请求

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "title": "Rustic Ceramic & Leather Leaves Necklace",
      }
   },
   "output_spec": {
      "workflow_id": "description"
   }
}

响应

{
  "description": {
    "text": "Rustic Ceramic & Leather Leaves Necklace is a beautiful necklace made from high-quality ceramic and leather. It features a unique design that is sure to turn heads.
"
  },
}

根据商品属性(例如品牌和颜色)生成商品名和说明

此示例演示了如何提供商品属性以生成最佳商品名和说明。

请求

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "brand": "Mr. Beast",
         "color": "purple",
      },
      "product_image":{
         "uri": "https://mrbeast.store/cdn/shop/files/0015dlv_0000_327.jpg?v=1702754475&width=500"
       }
   },
   "output_spec": {
      "workflow_id": "description"
   }
}

响应

{
  "title": {
    "text": "Pajamas - Mr. Beast | Purple"
  },
  "description": {
    "text": "Slip into the ultimate comfort and style with these Mr. Beast pajamas in a vibrant shade of purple. Crafted from the softest materials, these pajamas will envelop you in a cozy embrace, ensuring a restful night's sleep. The shorts feature a relaxed fit, allowing for easy movement, while the top boasts a classic design with a comfortable neckline. Whether you're lounging at home or drifting off to dreamland, these Mr. Beast pajamas are the perfect choice for a peaceful and stylish slumber."
  },
}

目标语言支持

此字段指定 API 响应中生成的说明文本的语言。您可以将 target_language 添加为 output_spec 参数的一部分:

{
    "output_spec": {
        "target_language": "language"
    }
}

示例值:

"korean" (Korean)
"english" (English)
"spanish" (Spanish)
"french" (French)

示例请求

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "title": "Granos de café negro",
         "description": "Los granos de café negro en California",
         "brand": "Parfums de Paris",
         "scent": "Floral",
      },
      "product_image":{
         "uri": "https://mrbeast.store/cdn/shop/files/0015dlv_0000_327.jpg?v=1702754475&width=500"
       }
   },
   "output_spec": {
      "workflow_id": "description",
      "target_language": "japanese",
      "attribute_order": ["scent", "product"],
      "tone": "playful",
   }
}

响应

{
  "description": {
    "text": "カリフォルニアの黒いコーヒー豆は、あなたの鼻をくすぐる、甘く、フローラルな香りです。この香りは、コーヒー豆の豊かな香りと、ジャスミンとバラの繊細な花の香りをブレンドしたものです。カリフォルニアの黒いコーヒー豆は、あなたの家を居心地の良いカフェに変え、あなたをリラックスした気分にさせてくれるでしょう。この香りは、コーヒー好きにも、フローラルな香り好きにも最適です。カリフォルニアの黒いコーヒー豆で、あなたの家を幸せな香りで満たしましょう!."
  },
}

为说明生成功能提供语气个性化设置

为了帮助您树立品牌形象并使您的网店与众不同,您可以对生成的说明的语气进行个性化设置。Text API 提供了两个选项:

  • 预定义语气选择: 您可以从语气列表中进行选择,以生成新的说明。该列表包含以下语气样式:
    • 默认: 简单、清晰、优雅。
    • 俏皮: 轻松愉快,使用积极的语言、幽默(笑话、双关语)和夸张(不含讽刺、挖苦或表情符号)。
    • 正式: 标准英语、正确的语法、完整的句子,不使用俚语或缩写。
    • 有说服力: 逻辑严谨、简洁明了、以论证为导向,旨在说服读者。
    • 对话式: 友好、易于理解、日常用语。
  • 品牌专属语气: 您可以提供现有说明或采用品牌语气的其他文本素材。生成式 AI 模型将分析文本的语气,并根据以下方面生成“写作风格描述符”:
    • 用语正式程度 (例如,正式、随意)
    • 详细程度 (例如,简洁、非常详细)
    • 语气 (例如,专业、博学、积极、有说服力)
    • 句子结构 (例如,“使用少量连词的简单句子”)
    • 最常用的字词和短语

客户端库

我们建议您使用客户端库提交请求。我们将与您分享客户端库,您可以在 Maven 项目中安装这些库。

代码示例

选择您的身份验证方法,并按照这些说明设置这些代码示例。 以下是一个可用于生成文本建议的示例。

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.productstudio.v1alpha.GenerateProductTextSuggestionsRequest;
import com.google.shopping.merchant.productstudio.v1alpha.GenerateProductTextSuggestionsResponse;
import com.google.shopping.merchant.productstudio.v1alpha.OutputSpec;
import com.google.shopping.merchant.productstudio.v1alpha.ProductInfo;
import com.google.shopping.merchant.productstudio.v1alpha.TextSuggestionsServiceClient;
import com.google.shopping.merchant.productstudio.v1alpha.TextSuggestionsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to generate product text suggestions. */
public class GenerateProductTextSuggestionsSample {

  private static String getName(String accountId) {
    return String.format("accounts/%s", accountId);
  }

  public static void generateProductTextSuggestions(Config config) throws Exception {
    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    TextSuggestionsServiceSettings textSuggestionsServiceSettings =
        TextSuggestionsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String name = getName(config.getAccountId().toString());

    // Calls the API and catches and prints any network failures/errors.
    try (TextSuggestionsServiceClient textSuggestionsServiceClient =
        TextSuggestionsServiceClient.create(textSuggestionsServiceSettings)) {

      ProductInfo productInfo =
          ProductInfo.newBuilder()
              .putProductAttributes("title", "Mens shirt")
              .putProductAttributes("description", "A blue shirt for men in size S")
              .build();

      OutputSpec outputSpec = OutputSpec.newBuilder().setWorkflowId("title").build();

      GenerateProductTextSuggestionsRequest request =
          GenerateProductTextSuggestionsRequest.newBuilder()
              .setName(name)
              .setProductInfo(productInfo)
              .setOutputSpec(outputSpec)
              .build();

      System.out.println("Sending GenerateProductTextSuggestions request: " + name);
      GenerateProductTextSuggestionsResponse response =
          textSuggestionsServiceClient.generateProductTextSuggestions(request);
      System.out.println("Generated product text suggestions response below:");
      System.out.println(response);
    } catch (Exception e) {
      System.out.println("An error has occured: ");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    generateProductTextSuggestions(config);
  }
}

Python

"""A module to generate product text suggestions."""

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_productstudio_v1alpha import GenerateProductTextSuggestionsRequest
from google.shopping.merchant_productstudio_v1alpha import OutputSpec
from google.shopping.merchant_productstudio_v1alpha import ProductInfo
from google.shopping.merchant_productstudio_v1alpha import TextSuggestionsServiceClient


# Fetches the Merchant Center account ID from the configuration file.
# This ID is used to construct the 'name' for the API request.
_ACCOUNT_ID = configuration.Configuration().read_merchant_info()
# The parent resource name for the GenerateProductTextSuggestionsRequest.
# Format: "accounts/{account}"
_PARENT_RESOURCE_NAME = f"accounts/{_ACCOUNT_ID}"


def generate_product_text_suggestions_sample():
  """Generates product text suggestions for a given product."""

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client for the TextSuggestionsService.
  client = TextSuggestionsServiceClient(credentials=credentials)

  # Defines the product information for which suggestions are needed.
  # This includes attributes like title and description.
  product_info = ProductInfo(
      product_attributes={
          "title": "Mens shirt",
          "description": "A blue shirt for men in size S",
      }
  )

  # Defines the output specification.
  # The 'workflow_id' specifies the type of text suggestion, e.g., "title".
  output_spec = OutputSpec(workflow_id="title")

  # Creates the request object for generating product text suggestions.
  # It includes the parent resource name, product information, and output
  # specification.
  request = GenerateProductTextSuggestionsRequest(
      name=_PARENT_RESOURCE_NAME,
      product_info=product_info,
      output_spec=output_spec,
  )

  # Sends the request to the API.
  print(
      f"Sending GenerateProductTextSuggestions request: {_PARENT_RESOURCE_NAME}"
  )
  try:
    response = client.generate_product_text_suggestions(request=request)
    # Prints the generated suggestions.
    print("Generated product text suggestions response below:")
    print(response)
  except RuntimeError as e:
    # Catches and prints any errors that occur during the API call.
    print("An error has occured: ")
    print(e)


if __name__ == "__main__":
  generate_product_text_suggestions_sample()

常见错误和问题

以下是一些常见的陷阱及其解决方案。

生成文本建议需要商品信息

如果您收到以下错误消息

Error message:
"error": {
    "code": 400,
    "message": "[product_info] Product info is required to generate text suggestions.",
    "status": "INVALID_ARGUMENT",
 ...
}

请在请求正文中添加 product_info,并正确填充至少一个 product_attributesproduct_image

例如,发布此内容会导致错误。

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "output_spec": {
      "workflow_id": "title"
   }
}

生成文本建议需要至少一个 product_info 字段

此错误

{
  "error": {
    "code": 400,
    "message": "[product_info.product_attributes] At least one field of product_info is required to generate text suggestions.",
    "status": "INVALID_ARGUMENT",
 ...
}

表示您需要在请求正文中添加至少一个 product_info 字段。

例如,发布此内容会导致错误。

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
   },
   "output_spec": {
      "workflow_id": "title"
   }
}

请改用类似如下的内容

   "product_info": {
        "product_attributes": {
         "description": "Selling size 12 Nike dunks. Oh they are red by the way!"
      }
   }

"product_info": {
    "product_image":{
        "uri": "https://cdn.shopify.com/s/files/1/0653/5879/0892/products/1672082339438_550x825.jpg?v=1672082415"
    }
}

每个 title_example 中都需要(内容)

以下四个示例中的错误

{
  "error": {
    "code": 400,
    "message": "[title_examples.product_info] At least one field of product_info is required in each title_example.",
    "status": "INVALID_ARGUMENT",
 ...
}

{
  ...
    "message": "[title_examples.category] Category is required in each title_example.",
  ...
}

{
  ...
    "message": "[title_examples.title_format] Title format is required in each title_example.",
  ...
}

{
  ...
    "message": "[title_examples.final_product_info] At least one field of final_product_info is required in each title_example.",
  ...
}

表示您尚未填充必填的子字段。

例如,以下请求会生成错误。

POST
https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
    "product_info": {
        "product_attributes": {
            "description": "selling size 12 nike dunks. oh they are red by the way!"
        }
    },
    "output_spec": {
        "workflow_id": "title"
    },
    "title_examples": []
}

如需解决此问题,请为请求中指定的每个 title_example 填充以下所有子字段:

  • product_info
  • category
  • title_format
  • final_product_info

以下是一个有效示例:

{
   "product_info": {
      "product_attributes": {
         "title": "Volumizing & Lengthening Mascara - Dark Brown",
         "description": "This high-impact mascara delivers both voluptuous volume and dramatic length without clumping or smudging.",
      }
   },
   "output_spec": {
      "workflow_id": "title"
   },
   "title_examples": [
    {
      "product_info": {
        "title": "Lash Paradise Volumizing & Lengthening Mascara - Waterproof - Blackest Black",
        "colour": "Black"
      },
      "title_format": "product",
      "category": "mascara",
      "final_product_info": {
        "product": "Mascara",
        "brand": "Lash Paradise",
        "mascara_type": "Volumizing & Lengthening",
        "colour": "Blackest Black",
        "waterproof": "Waterproof",
      }
    }
  ]
}

workflow_id 不受支持

此类错误

{
  "error": {
    "code": 400,
    "message": "[\u003ceye3 title='/ProductStudioTextGenerationService.GenerateProductText, INVALID_ARGUMENT'/\u003e APPLICATION_ERROR; ... ;Unsupported workflow_id: attributes. Supported workflows are: [\"title\", \"description\", \"tide\"];AppErrorCode=3;StartTimeMs=1740696804045;unknown;ResFormat=uncompressed;ServerTimeSec=0.005976589;LogBytes=256;Non-FailFast;EffSecLevel=none;ReqFormat=uncompressed;ReqID=4d1786f59faa3ea7;GlobalID=0;Server=[2002:a05:6e16:618:b0:2c2:7cfc:bebd]:14001] Invalid value",
    "status": "INVALID_ARGUMENT",
 ...
}

是由如下请求导致的

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "title": "Volumizing & Lengthening Mascara - Dark Brown",
         "description": "This high-impact mascara delivers both voluptuous volume and dramatic length without clumping or smudging.",
   },
   "output_spec": {
      "workflow_id": "attributes"
   }
}

该请求将 workflow_id 设置为“attributes”,但此字段仅支持以下值之一:

  • title:生成或优化商品名。
  • description:生成或优化商品说明。
  • tide:同时生成或优化商品名和说明。

语气不受支持

“语气不受支持”错误,例如

{
  "error": {
    "code": 400,
    "message": "[\u003ceye3 title='/ProductStudioTextGenerationService.GenerateProductText, INVALID_ARGUMENT'/\u003e APPLICATION_ERROR; ... ; Unsupported tone: 'asdf'. Supported tones are: [\"default\", \"playful\", \"formal\", \"persuasive\", \"conversational\"];AppErrorCode=3;StartTimeMs=1740697325058;unknown;ResFormat=uncompressed;ServerTimeSec=7.45346E-4;LogBytes=256;Non-FailFast;EffSecLevel=none;ReqFormat=uncompressed;ReqID=f7d9bbbc73a1d342;GlobalID=0;Server=[2002:a05:6918:3486:b0:2bc:ccd4:79e6]:14001] Invalid value",
    "status": "INVALID_ARGUMENT",
 ...
}

是由如下请求导致的

POST https://merchantapi.googleapis.com/productstudio/v1alpha/accounts/{ACCOUNT_ID}:generateProductTextSuggestions

{
   "product_info": {
      "product_attributes": {
         "title": "Volumizing & Lengthening Mascara - Dark Brown",
         "description": "This high-impact mascara delivers both voluptuous volume and dramatic length without clumping or smudging.",
   },
   "output_spec": {
      "workflow_id": "description"
      "tone": "cheerful"
   }
}

请注意,tone 设置为“cheerful”,但此字段仅支持以下值之一:

  • default:简单、清晰、优雅。
  • playful:轻松愉快,使用积极的语言、幽默(笑话、双关语)和 夸张(不含讽刺、挖苦或表情符号)。
  • 正式程度:标准英语、正确的语法、完整的句子,不使用俚语 或缩写。
  • persuasive:逻辑严谨、简洁明了、以论证为导向,旨在说服 读者。
  • conversational:友好、易于理解、日常用语。