Генерировать варианты текста

Text Suggestions API использует генеративные ИИ-инструменты Product Studio API, чтобы создавать и оптимизировать названия и описания товаров. Это позволяет повысить вовлеченность клиентов и количество конверсий, а также упростить управление информацией о товарах и ее обновление. Функции Product Studio API помогут вам оптимизировать эффективность розничной торговли.

Что можно сгенерировать с помощью API?

Text Suggestions API позволяет:

  • Варианты названий и описаний товаров, созданные на основе изображений и/или атрибутов товаров.
  • Оптимизированные для поиска названия товаров
  • Названия товаров в специальном формате
  • описания товаров из фида товаров

Вы также можете указать тон описаний и поддерживать единообразие во всех списках товаров.

Краткое руководство

Метод 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 – определяет порядок атрибутов в созданном названии.
  • Примеры разметки данных. Посмотрите пример того, как создать заголовок на основе описания.
  • Идентификатор рабочего процесса (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"
      },
    }
  }
}

Оптимизация названий на основе названия и описания (с примером)

В этом примере мы явно помечаем атрибуты товара, которые должен определить ИИ, и порядок атрибутов в выходных данных.

Запрос

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 предлагает два варианта:

  • Выбор тона. Вы можете выбрать тон из списка, чтобы сгенерировать новые описания. В списке есть следующие стили:
    • По умолчанию. Простой, понятный и элегантный.
    • Игривый. Легкий, с позитивной лексикой, юмором (шутки, каламбуры) и преувеличениями (без иронии, сарказма и эмодзи).
    • Формальный. Стандартный английский язык, правильная грамматика, полные предложения, без сленга и сокращений.
    • Убедительный. Логичный, лаконичный и аргументированный, чтобы убедить читателя.
    • Разговорный. Дружелюбный, понятный, повседневный язык.
  • Тон бренда. Вы можете предоставить существующие описания или другие текстовые объекты, написанные в тоне вашего бренда. Модель генеративного ИИ проанализирует тон текста и создаст дескриптор стиля письма на основе следующих аспектов:
    • Уровень формальности (например, формальный или неформальный).
    • Детализация (например, кратко, очень подробно).
    • Тон (например, профессиональный, информативный, позитивный, убедительный).
    • Структура предложений (например, "простые предложения с небольшим количеством союзов").
    • Наиболее часто используемые слова и фразы

Клиентские библиотеки

Для отправки запросов рекомендуем использовать клиентские библиотеки. Мы предоставим вам клиентские библиотеки, которые вы сможете установить в своем проекте 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_attributes или product_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"
    }
}

(Something) is required in each 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",
      }
    }
  ]
}

Неподдерживаемый идентификатор рабочего процесса

Такая ошибка

{
  "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: простой, понятный и элегантный.
  • Игривый. Беззаботный, с использованием позитивной лексики, юмора (шуток, каламбуров) и преувеличений (без иронии, сарказма и эмодзи).
  • formal: стандартный английский язык, правильная грамматика, полные предложения, без сленга и сокращений.
  • Убедительный. Логичный, лаконичный и аргументированный текст, который убеждает читателя.
  • Разговорный. Дружелюбный, понятный, повседневный язык.