Biblioteca de queries
Biblioteca de queriesMelhorando automaticamente a descrição de um novo produto WooCommerce com ChatGPT

Melhorando automaticamente a descrição de um novo produto WooCommerce com ChatGPT

Esta query busca o produto WooCommerce com o ID fornecido, reescreve seu conteúdo usando ChatGPT e o armazena novamente.

(Na próxima seção, automatizaremos a execução desta query sempre que um produto for criado.)

O Custom Post Type product do WooCommerce deve ser configurado como consultável via schema GraphQL, conforme explicado no guia Permitindo acesso a Custom Post Types.

Para isso, vá à página de Configurações, clique na aba "Schema Elements Configuration > Custom Posts" e selecione product na lista de CPTs consultáveis (se ainda não estiver selecionado).

Para conectar-se à API da OpenAI, você deve fornecer a variável $openAIAPIKey com a chave de API.

Você pode opcionalmente fornecer a mensagem do sistema e o prompt para reescrever o conteúdo do post. Se não fornecidos, os seguintes valores são usados:

  • Mensagem do sistema ($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: "

(A string de conteúdo é adicionada ao final do prompt.)

Além disso, você pode sobrescrever o valor padrão para as variáveis $model ("gpt-4o-mini", confira a lista de modelos da OpenAI) e fornecer valores para $temperature e $maxCompletionTokens (ambos null por padrão).

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
      }
    }
  }
}

Automatizando o processo

Podemos usar o Internal GraphQL Server para executar automaticamente a query sempre que um novo produto WooCommerce for criado.

Para isso, primeiro crie uma nova query persistida com o título "Improve Product Content With ChatGPT" (isso atribuirá o slug improve-product-content-with-chatgpt), e a query GraphQL acima.

Em seguida, em qualquer lugar da sua aplicação (por exemplo: no arquivo functions.php, em um plugin, ou em um snippet de código), adicione o seguinte código PHP, que executa a query no hook 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
);