Bibliothèque de queries
Bibliothèque de queriesRemplir une page Bricks avec du texte généré par Claude

Remplir une page Bricks avec du texte généré par Claude

Cette requête génère et injecte dynamiquement du contenu dans votre page Bricks en utilisant Claude.

Pour créer le contenu, nous devons fournir un sujet via la variable $topic, que nous passons à Claude pour qu'il génère l'ensemble du contenu.

Le nouveau contenu est injecté dans tous les éléments heading, text et text-basic.

Cette requête nécessite que l'extension Bricks soit activée.

La requête nécessite les variables suivantes :

  • $customPostId: L'ID du post personnalisé Bricks à mettre à jour
  • $anthropicAPIKey: La clé API pour l'API Anthropic
  • $topic: Le sujet pour lequel générer du contenu
query InitializeVariables
  @configureWarningsOnExportingDuplicateVariable(enabled: false)
{
  emptyArray: _echo(value: [])
    @export(as: "elementHeadingIDs")
    @export(as: "elementHeadings")
    @export(as: "elementTextIDs")
    @export(as: "elementTexts")
    @export(as: "elementTextBasicIDs")
    @export(as: "elementTextBasics")
}
 
query GetBricksData($customPostId: ID!)
  @depends(on: "InitializeVariables")
{
  customPostForContainerHeadings: customPost(by:{ id: $customPostId }, status: any) {
    id
    title
    bricksDataHeading: bricksData(filterBy: { include: ["heading"] })
      @underEachArrayItem(affectDirectivesUnderPos: [1, 3])
        @underJSONObjectProperty(by: { key: "id" })
          @export(as: "elementHeadingIDs")
        @underJSONObjectProperty(by: { path: "settings.text" })
          @export(as: "elementHeadings")
    bricksDataText: bricksData(filterBy: { include: ["text"] })
      @underEachArrayItem(affectDirectivesUnderPos: [1, 3])
        @underJSONObjectProperty(by: { key: "id" })
          @export(as: "elementTextIDs")
        @underJSONObjectProperty(by: { path: "settings.text" })
          @export(as: "elementTexts")
    bricksDataTextBasic: bricksData(filterBy: { include: ["text-basic"] })
      @underEachArrayItem(affectDirectivesUnderPos: [1, 3])
        @underJSONObjectProperty(by: { key: "id" })
          @export(as: "elementTextBasicIDs")
        @underJSONObjectProperty(by: { path: "settings.text" })
          @export(as: "elementTextBasics")
  }
}
 
query GenerateContentWithClaude(
  $topic: NonEmptyString!
  $anthropicAPIKey: String!
  $maxTokens: Int! = 32000
  $promptTemplate: String! = """
You are content writer.
 
I need to generate content for a WordPress page using Bricks.
 
Based on the following topic, please generate:
1. Headings: A list with {$elementHeadingsNumber} headings (max 60 chars)
2. Basic texts: A list with {$elementTextsNumber} descriptions in plain format (max 300 chars)
3. HTML texts: A list with {$elementTextBasicsNumber} descriptions containing HTML (max 300 chars)
 
Please respond in JSON format with this structure:
{
  "headings": ["Heading 1", "Heading 2", "Heading 3"],
  "basicTexts": ["Basic text 1", "Basic text 2", "Basic text 3"],
  "htmlTexts": ["<p>HTML text 1</p>", "<p>HTML text 2</p>", "<p>HTML text 3</p>"]
}
 
Return ONLY the JSON object. Do not include any explanations, markdown formatting, or code blocks. The response must be a valid JSON object starting with { and ending with }.
 
Topic to analyze:
 
{$topic}
"""
  $model: String! = "claude-sonnet-4-0"
)
  @depends(on: "GetBricksData")
{
  elementHeadingsNumber: _arrayLength(array: $elementHeadings)
  elementTextsNumber: _arrayLength(array: $elementTexts)
  elementTextBasicsNumber: _arrayLength(array: $elementTextBasics)
  prompt: _strReplaceMultiple(
    search: [
      "{$topic}",
      "{$elementHeadingsNumber}",
      "{$elementTextsNumber}",
      "{$elementTextBasicsNumber}"
    ],
    replaceWith: [
      $topic,
      $__elementHeadingsNumber,
      $__elementTextsNumber,
      $__elementTextBasicsNumber
    ],
    in: $promptTemplate
  )
  claudeResponse: _sendJSONObjectItemHTTPRequest(input: {
    url: "https://api.anthropic.com/v1/messages",
    method: POST,
    options: {
      headers: [
        {
          name: "x-api-key",
          value: $anthropicAPIKey
        },
        {
          name: "anthropic-version",
          value: "2023-06-01"
        }
      ],
      json: {
        model: $model,
        max_tokens: $maxTokens,
        messages: [
          {
            role: "user",
            content: $__prompt
          }
        ],
      }
    }
  })
    @underJSONObjectProperty(by: { key: "content" })
      @underArrayItem(index: 0)
        @underJSONObjectProperty(by: { key: "text" })
          @export(as: "jsonEncodedContent")
}
 
query ExtractContent
  @depends(on: "GenerateContentWithClaude")
{
  jsonEncodedContent: _echo(value: $jsonEncodedContent)
    @remove
  decodedContent: _strDecodeJSONObject(string: $jsonEncodedContent)
  createdElementHeadings: _objectProperty(object: $__decodedContent, by: { key: "headings" })
  createdElementTexts: _objectProperty(object: $__decodedContent, by: { key: "basicTexts" })
  createdElementTextBasics: _objectProperty(object: $__decodedContent, by: { key: "htmlTexts" })
  
  elementIDs: _arrayMerge(arrays: [
    $elementHeadingIDs,
    $elementTextIDs,
    $elementTextBasicIDs
  ])
    @export(as: "elementIDs")
  elementTexts: _arrayMerge(arrays: [
    $__createdElementHeadings,
    $__createdElementTexts,
    $__createdElementTextBasics
  ])
    @export(as: "elementTexts")
}
 
query GetMergeInputData
  @depends(on: "ExtractContent")
{
  elementToUpdateMergeInputElements: _echo(value: $elementIDs)
    @underEachArrayItem(
      passIndexOnwardsAs: "index",
      passValueOnwardsAs: "id"
      affectDirectivesUnderPos: [1, 2]
    )
      @applyField(
        name: "_arrayItem",
        arguments: {
          array: $elementTexts,
          position: $index
        },
        passOnwardsAs: "text"
      )
      @applyField(
        name: "_echo",
        arguments: {
          value: {
            id: $id,
            settings: {
              text: $text
            }
          }
        }
        setResultInResponse: true
      )
    @export(as: "elementToUpdateMergeInputElements")
}
 
mutation StoreUpdatedElementText($customPostId: ID!)
  @depends(on: "GetMergeInputData")
{
  bricksMergeCustomPostElementDataItem(input: {
    customPostID: $customPostId
    elements: $elementToUpdateMergeInputElements
  }) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
          @passOnwards(as: "message")
          @fail(
            message: $message
            condition: ALWAYS
          )
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        bricksData
      }
    }
  }
}