Библиотека queries
Библиотека queriesАвтоматическое улучшение описания нового продукта WooCommerce с помощью ChatGPT

Автоматическое улучшение описания нового продукта WooCommerce с помощью ChatGPT

Этот запрос получает продукт WooCommerce по указанному ID, переписывает его содержимое с помощью ChatGPT и сохраняет обратно.

(В следующем разделе мы автоматизируем выполнение этого запроса при каждом создании продукта.)

Custom Post Type product из WooCommerce должен быть доступен для запросов через схему GraphQL, как описано в руководстве Разрешение доступа к Custom Post Types.

Для этого перейдите на страницу настроек, нажмите вкладку «Schema Elements Configuration > Custom Posts» и выберите product из списка доступных для запросов CPT (если он ещё не выбран).

Для подключения к API OpenAI необходимо передать переменную $openAIAPIKey с ключом API.

Опционально можно передать системное сообщение и prompt для переписывания содержимого записи. Если они не заданы, используются следующие значения:

  • Системное сообщение ($systemMessage): "You are an English Content rewriter and a grammar checker"
  • Prompt ($prompt): "Please rewrite the following English text, by changing the simple A0-level words and sentences with more beautiful and elegant upper-level English words and sentences, while maintaining the original meaning: "

(Строка с содержимым добавляется в конец prompt.)

Кроме того, можно переопределить значение по умолчанию для переменной $model ("gpt-4o-mini", см. список моделей OpenAI), а также задать значения для $temperature и $maxCompletionTokens (оба по умолчанию равны null).

query GetProductContent(
  $productId: ID!
) {
  customPost(by: { id: $productId }, customPostTypes: "product", status: any) {
    content
      @export(as: "content")
  }
}
 
query RewriteProductContentWithChatGPT(
  $openAIAPIKey: String!
  $systemMessage: String! = "You are an English Content rewriter and a grammar checker"
  $prompt: String! = "Please rewrite the following English text, by changing the simple A0-level words and sentences with more beautiful and elegant upper-level English words and sentences, while maintaining the original meaning: "
  $model: String! = "gpt-4o-mini"
  $temperature: Float
  $maxCompletionTokens: Int
)
  @depends(on: "GetProductContent")
{
  promptWithContent: _strAppend(
    after: $prompt
    append: $content  
  )
  openAIResponse: _sendJSONObjectItemHTTPRequest(input: {
    url: "https://api.openai.com/v1/chat/completions",
    method: POST,
    options: {
      auth: {
        password: $openAIAPIKey
      },
      json: {
        model: $model,
        temperature: $temperature,
        max_completion_tokens: $maxCompletionTokens,
        messages: [
          {
            role: "system",
            content: $systemMessage
          },
          {
            role: "user",
            content: $__promptWithContent
          }
        ]
      }
    }
  })
    @underJSONObjectProperty(by: { key: "choices" })
      @underArrayItem(index: 0)
        @underJSONObjectProperty(by: { path: "message.content" })
          @export(as: "rewrittenContent")
}
 
mutation UpdateProduct(
  $productId: ID!
)
  @depends(on: "RewriteProductContentWithChatGPT")
{
  updateCustomPost(input: {
    id: $productId,
    customPostType: "product"
    contentAs: {
      html: $rewrittenContent
    }
  }) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        content
      }
    }
  }
}

Автоматизация процесса

Можно использовать Internal GraphQL Server для автоматического выполнения запроса при каждом создании нового продукта WooCommerce.

Для этого сначала создайте новый persisted query с заголовком "Improve Product Content With ChatGPT" (это присвоит ему slug improve-product-content-with-chatgpt) и указанным выше GraphQL-запросом.

Затем в любом месте вашего приложения (например, в файле functions.php, плагине или фрагменте кода) добавьте следующий PHP-код, который выполняет запрос на хуке publish_product:

use GatoGraphQL\InternalGraphQLServer\GraphQLServer;
 
add_action(
  'publish_product',
  function (int $productId, WP_Post $post, string $oldStatus): void {
    // Only execute when it's a newly-published product
    if ($oldStatus === 'publish') {
      return;
    }
 
    GraphQLServer::executePersistedQuery('improve-product-content-with-chatgpt', [
      'productId' => $productId,
 
      // Provide your Open AI's API Key
      'openAIAPIKey' => '{ OPENAI_API_KEY }',
 
      // Customize any of the other variables, for instance:
      'maxCompletionTokens' => 5000,
    ]);
  }, 10, 3
);