Queries-Bibliothek
Queries-BibliothekAutomatisches Verbessern der Beschreibung eines neuen WooCommerce-Produkts mit ChatGPT

Automatisches Verbessern der Beschreibung eines neuen WooCommerce-Produkts mit ChatGPT

Diese query ruft das WooCommerce-Produkt mit der angegebenen ID ab, schreibt dessen Inhalt mithilfe von ChatGPT neu und speichert ihn wieder.

(Im nächsten Abschnitt automatisieren wir die Ausführung dieser query, sobald ein Produkt erstellt wird.)

Der Custom Post Type product von WooCommerce muss über das GraphQL-Schema abfragbar gemacht werden, wie in der Anleitung Zugriff auf Custom Post Types erlauben erklärt.

Gehe dazu zur Einstellungsseite, klicke auf den Tab "Schema Elements Configuration > Custom Posts" und wähle product aus der Liste der abfragbaren CPTs aus (falls es nicht bereits ausgewählt ist).

Um eine Verbindung zur OpenAI-API herzustellen, musst du die Variable $openAIAPIKey mit dem API-Schlüssel angeben.

Du kannst optional die Systemnachricht und den Prompt angeben, um den Inhalt des Beitrags neu zu schreiben. Wenn keine Werte angegeben werden, werden folgende Standardwerte verwendet:

  • Systemnachricht ($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: "

(Der Inhaltsstring wird am Ende des Prompts angehängt.)

Außerdem kannst du den Standardwert für die Variablen $model ("gpt-4o-mini", siehe die Liste der OpenAI-Modelle) überschreiben und Werte für $temperature und $maxCompletionTokens angeben (beide standardmäßig 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
      }
    }
  }
}

Den Prozess automatisieren

Wir können den Internal GraphQL Server verwenden, um die query automatisch auszuführen, sobald ein neues WooCommerce-Produkt erstellt wird.

Dazu erstelle zunächst eine neue persisted query mit dem Titel "Improve Product Content With ChatGPT" (dadurch wird ihr der Slug improve-product-content-with-chatgpt zugewiesen) und der obigen GraphQL-query.

Füge dann an einer beliebigen Stelle in deiner Anwendung (z. B. in deiner functions.php-Datei, einem Plugin oder einem Code-Snippet) den folgenden PHP-Code hinzu, der die query beim Hook publish_product ausführt:

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
);