Libreria di queries
Libreria di queriesMigliorare automaticamente la descrizione di un nuovo prodotto WooCommerce con ChatGPT

Migliorare automaticamente la descrizione di un nuovo prodotto WooCommerce con ChatGPT

Questa query recupera il prodotto WooCommerce con l'ID fornito, riscrive il suo contenuto utilizzando ChatGPT e lo salva nuovamente.

(Nella sezione successiva, automatizzeremo l'esecuzione di questa query ogni volta che viene creato un prodotto.)

Il Custom Post Type product di WooCommerce deve poter essere interrogato tramite lo schema GraphQL, come spiegato nella guida Consentire l'accesso ai Custom Post Types.

Per farlo, vai alla pagina delle Impostazioni, fai clic sulla scheda "Schema Elements Configuration > Custom Posts" e seleziona product dall'elenco dei CPT interrogabili (se non è già selezionato).

Per connetterti all'API di OpenAI, devi fornire la variabile $openAIAPIKey con la chiave API.

Puoi facoltativamente fornire il messaggio di sistema e il prompt per riscrivere il contenuto del post. Se non vengono forniti, vengono utilizzati i seguenti valori:

  • Messaggio di 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 stringa del contenuto viene aggiunta alla fine del prompt.)

Inoltre, puoi sovrascrivere il valore predefinito per le variabili $model ("gpt-4o-mini", consulta la lista dei modelli OpenAI) e fornire valori per $temperature e $maxCompletionTokens (entrambi null per impostazione predefinita).

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

Automatizzare il processo

Possiamo utilizzare l'Internal GraphQL Server per eseguire automaticamente la query ogni volta che viene creato un nuovo prodotto WooCommerce.

Per farlo, prima crea una nuova query persistita con il titolo "Improve Product Content With ChatGPT" (questo le assegnerà lo slug improve-product-content-with-chatgpt), e la query GraphQL qui sopra.

Poi, in qualsiasi punto della tua applicazione (ad esempio nel file functions.php, un plugin, o uno snippet di codice), aggiungi il seguente codice PHP, che esegue la query sull'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
);