Biblioteca de queries
Biblioteca de queriesMejorar automáticamente la descripción de un nuevo producto de WooCommerce con ChatGPT

Mejorar automáticamente la descripción de un nuevo producto de WooCommerce con ChatGPT

Esta consulta obtiene el producto de WooCommerce con el ID indicado, reescribe su contenido usando ChatGPT y lo guarda de nuevo.

(En la siguiente sección automatizaremos la ejecución de esta consulta cada vez que se cree el producto.)

El Custom Post Type product de WooCommerce debe poder consultarse a través del esquema de GraphQL, tal y como se explica en la guía Permitir el acceso a los Custom Post Types.

Para ello, ve a la página de Configuración, haz clic en la pestaña "Schema Elements Configuration > Custom Posts" y selecciona product de la lista de CPTs consultables (si no estuviera ya seleccionado).

Para conectar con la API de OpenAI, debes proporcionar la variable $openAIAPIKey con la clave de la API.

Opcionalmente puedes proporcionar el mensaje de sistema y el prompt para reescribir el contenido de la entrada. Si no se proporcionan, se utilizan los siguientes valores:

  • Mensaje de 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: "

(La cadena de contenido se añade al final del prompt.)

Además, puedes sobrescribir el valor por defecto de las variables $model ("gpt-4o-mini", consulta la lista de modelos de OpenAI) y proporcionar valores para $temperature y $maxCompletionTokens (ambos null por defecto).

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

Automatizar el proceso

Podemos utilizar el Internal GraphQL Server para ejecutar automáticamente la consulta cada vez que se crea un nuevo producto de WooCommerce.

Para ello, primero crea una nueva consulta persistida con el título "Improve Product Content With ChatGPT" (esto le asignará el slug improve-product-content-with-chatgpt) y la consulta GraphQL anterior.

Después, en cualquier parte de tu aplicación (por ejemplo, en tu archivo functions.php, en un plugin o en un fragmento de código), añade el siguiente código PHP, que ejecuta la consulta en el 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
);