Add embedding support

From diegosouzapw/awesome-omni-skill · View interactive version

Add embedding support is an AI agent skill from the GitHub repository diegosouzapw/awesome-omni-skill. Add Qdrant embedding support to v3 WordPress components for RAG chatbot. Implements component-level content chunking for searchable, structured embeddings. Use when adding embedding to new or existing v3 components.

How to use this skill

Skill file

Add Embedding Support Skill

You are helping add Qdrant embedding support to WordPress v3 components. This enables component content to be indexed

and searched via a RAG-based chatbot powered by Claude's API.

System Overview

The embedding system:

How It Works

  1. CLI command wp vendi embedding:generate runs
  2. Sets global constant VENDI_RENDER_CONTEXT to RenderingContextEnum::EMBEDDING
  3. Loads each component via vendi_load_component_v3()
  4. Template detects context and returns component instance (no HTML rendering)
  5. Component's getEmbedding() method extracts structured data
  6. ComponentEmbedding DTO formats data into JSON chunks for Qdrant

Output Format

Each component produces a JSON object like this:

{
  "content": "Heading: Ask a Researcher\nBody: Are you a CRNA with research questions?\nLinks: Contact us",
  "metadata": {
    "type": "page",
    "url": "https://example.com/page/",
    "created": "2022-11-29T21:01:08+00:00",
    "updated": "2024-03-07T09:07:06+00:00",
    "links": [
      {
        "text": "Contact us",
        "url": "https://example.com/contact/"
      }
    ],
    "component_type": "content_callout_full_width"
  },
  "id": "660-3"
}

Component Type Classification

Embeddable Components

Skippable Components

Simple Components

Complex Components


Implementation Patterns

Pattern 1: Simple Component (Single Chunk)

When to use: Component has just heading and/or body copy, no repeater fields

Choosing the Right Interfaces

IMPORTANT: Inspect the actual template file to determine which interfaces to implement:

The interfaces should map to what actually exists in the template structure.

Required Interfaces

use Vendi\Theme\ComponentInterfaces\ComponentEmbeddingAwareInterface;
use Vendi\Theme\ComponentInterfaces\PrimaryHeadingInterface; // If template has top-level heading
use Vendi\Theme\ComponentInterfaces\PrimaryCopyInterface;    // If template has top-level copy
use Vendi\Theme\DTO\Embedding\ComponentEmbedding;
use Vendi\Theme\DTO\Embedding\ComponentEmbeddingInterface;

Class Implementation

class simple_component extends BaseComponent implements
    ComponentEmbeddingAwareInterface,
    PrimaryHeadingInterface,      // Only if template has top-level heading
    PrimaryCopyInterface          // Only if template has top-level copy
{
    public function getEmbedding(): ?ComponentEmbeddingInterface
    {
        return ComponentEmbedding::fromComponent($this);
    }

    public function getPrimaryHeadingText(): ?string
    {
        // Return the field that corresponds to the top-level heading in template
        return get_sub_field('headline');
    }

    public function getPrimaryCopy(): ?string
    {
        // Return the field that corresponds to the top-level copy in template
        return get_sub_field('copy');
    }
}

Output

Heading: [from getPrimaryHeadingText() if interface implemented]
Body: [from getPrimaryCopy() if interface implemented]

Key Points:


Pattern 2: Skippable Component (No Embedding)

When to use: Ads, navigation, forms, decorative/visual-only elements

Required Interface

use Vendi\Theme\ComponentInterfaces\ComponentEmbeddingSkipAwareInterface;

Class Implementation

class ad_component extends VendiComponent implements ComponentEmbeddingSkipAwareInterface
{
    // No getEmbedding() method needed
    // Component completely ignored during embedding generation
}

Key Points:


Pattern 3: Complex Component with Sections

When to use: Component has repeater or flexible content fields where each item should be a separate section

Required Interfaces

use Vendi\Theme\ComponentInterfaces\ComponentEmbeddingAwareInterface;
use Vendi\Theme\ComponentInterfaces\PrimaryHeadingInterface;
use Vendi\Theme\ComponentInterfaces\PrimaryCopyInterface;
use Vendi\Theme\DTO\Embedding\ComponentEmbedding;
use Vendi\Theme\DTO\Embedding\ComponentEmbeddingInterface;

Class Implementation

public function getEmbedding(): ?ComponentEmbeddingInterface
{
    // Start with base embedding (auto-extracts heading/body from interfaces)
    $ret = ComponentEmbedding::fromComponent($this);

    // Loop through repeater field
    while (have_rows('items')) {
        the_row();
        $layout = get_row_layout();

        // CRITICAL: Filter to relevant layouts only
        if (!in_array($layout, ['content_item', 'text_block'], true)) {
            continue;
        }

        $heading = get_sub_field('heading');
        $copy = get_sub_field('copy');

        // CRITICAL: Always clean HTML from user content
        $cleanCopy = ComponentEmbedding::stripAllHtmlFromText($copy);

        // Add section with optional custom label
        $ret->addSection(
            $heading . PHP_EOL . $cleanCopy,
            'Section' // Optional: 'FAQ Item', 'Testimonial', etc.
        );
    }

    return $ret;
}

Output

Heading: [component main heading]
Body: [component intro copy]
Section 1: Item 1 Heading
[item 1 copy]
Section 2: Item 2 Heading
[item 2 copy]

Key Points:


Pattern 4: Component with Links/CTAs

When to use: Component has call-to-action buttons or links that should be tracked in metadata

Class Implementation

public function getEmbedding(): ?ComponentEmbeddingInterface
{
    $ret = ComponentEmbedding::fromComponent($this);

    while (have_rows('cards')) {
        the_row();

        $heading = get_sub_field('heading');
        $copy = get_sub_field('copy');
        $link = get_sub_field('cta');

        // Build structured content with labels
        $contentParts = [];
        if ($heading) {
            $contentParts[] = 'Heading: ' . $heading;
        }
        if ($copy) {
            $contentParts[] = 'Body: ' . $copy;
        }
        if ($link && is_array($link)) {
            $contentParts[] = 'Link: ' . $link['title'];
        }

        // Only add section if there's content
        if ($content = implode(PHP_EOL, array_filter($contentParts))) {
            $ret->addSection($content);
        }

        // CRITICAL: Track link separately in metadata
        if ($link && is_array($link)) {
            $ret->addLink(
                linkText: $link['title'] ?? '',
                linkUrl: $link['url'] ?? ''
            );
        }
    }

    return $ret;
}

Output

{
  "content": "Heading: Component Title\nBody: Intro text\nLinks: Card 1 CTA, Card 2 CTA\nSection 1:\nHeading: Card 1\nBody: Card 1 copy\nLink: Card 1 CTA",
  "metadata": {
    "links": [
      {
        "text": "Card 1 CTA",
        "url": "/page1/"
      },
      {
        "text": "Card 2 CTA",
        "url": "/page2/"
      }
    ],
    "component_type": "card_navigation"
  }
}

Key Points:


Pattern 5: Component with HTML Content Containing Links

When to use: Component has HTML content (bios, articles, descriptions) with embedded <a> tags that should be tracked

Class Implementation

public function getEmbedding(): ?ComponentEmbeddingInterface
{
    $ret = ComponentEmbedding::fromComponent($this);

    while (have_rows('items')) {
        the_row();

        $name = get_sub_field('name');
        $bio = get_sub_field('bio'); // Contains HTML with links

        // CRITICAL: Extract links BEFORE stripping HTML
        // Use name as prefix for context
        ComponentEmbedding::extractAndAddLinksFromHtml($ret, $bio, $name);

        // Now strip HTML for text content
        $cleanBio = ComponentEmbedding::stripAllHtmlFromText($bio);

        $ret->addSection(
            'Name: ' . $name . PHP_EOL . 'Bio: ' . $cleanBio,
            'Person'
        );
    }

    return $ret;
}

Output

If bio contains: <p>Follow me on <a href="https://twitter.com/jdoe">Twitter</a></p>

{
  "content": "Person 1: Name: John Doe\nBio: Follow me on Twitter",
  "metadata": {
    "links": [
      {"text": "John Doe Twitter", "url": "https://twitter.com/jdoe"}
    ]
  }
}

Key Points:


Pattern 6: Component with Related Posts

When to use: Component displays content from related WP_Post objects (testimonials, people, etc.)

Class Implementation

public function getEmbedding(): ?ComponentEmbeddingInterface
{
    $ret = ComponentEmbedding::fromComponent($this);

    foreach ($this->getRelatedPosts() as $post) {
        // CRITICAL: Validate post object before accessing fields
        if (!$post instanceof WP_Post) {
            continue;
        }

        $name = get_field('name', $post->ID);
        $bio = get_field('bio', $post->ID);

        // Clean HTML and add with custom section label
        $ret->addSection(
            $name . PHP_EOL . ComponentEmbedding::stripAllHtmlFromText($bio),
            'Person' // Custom label: 'Testimonial', 'Team Member', etc.
        );
    }

    return $ret;
}

Key Points:


Template File Requirements

CRITICAL: Every embeddable component template must include this boilerplate at the top.

Required Boilerplate

<?php

use Vendi\Theme\Component\{component_name};
use Vendi\Theme\ComponentUtility;
use Vendi\Theme\Enums\RenderingContextEnum;

/** @var {component_name} $component */
$component = ComponentUtility::get_new_component_instance({component_name}::class);

// CRITICAL: Early return for embedding context
if (defined('VENDI_RENDER_CONTEXT') && VENDI_RENDER_CONTEXT === RenderingContextEnum::EMBEDDING->value) {
    return $component;
}

if (!$component->renderComponentWrapperStart()) {
    return;
}

?>
    <!-- HTML template here -->
<?php

$component->renderComponentWrapperEnd();

Why This Matters

Without the embedding context check:

This boilerplate is required even for skippable components (for consistency).


Key Methods & Utilities

ComponentEmbedding Static Factory

`fromComponent($this)`

Purpose: Create base embedding with auto-extraction

Auto-extracts:

Usage: Always first line of getEmbedding()

public function getEmbedding(): ?ComponentEmbeddingInterface
{
    $ret = ComponentEmbedding::fromComponent($this);
    // ... add sections, links, etc.
    return $ret;
}

Note: The heading and body auto-extraction only works if you've implemented the corresponding interfaces based on what actually exists in the template (see Pattern 1 for details).

Content Building Methods

`addSection(string $text, string $sectionLabel = 'Section')`

Adds a labeled section to the embedding. Sections are auto-numbered (Section 1, Section 2, etc.).

Best Practice: Use descriptive labels

// Good: Descriptive
$ret->addSection($content, 'Testimonial');
$ret->addSection($content, 'FAQ Item');
$ret->addSection($content, 'Team Member');

// Acceptable: Default auto-numbering
$ret->addSection($content); // "Section 1", "Section 2", etc.

`addLink(string $linkText, string $linkUrl)`

Adds a link to metadata. Links stored separately from content text for advanced RAG features.

if ($link && is_array($link)) {
    $ret->addLink(
        linkText: $link['title'] ?? '',
        linkUrl: $link['url'] ?? ''
    );
}

`extractAndAddLinksFromHtml(ComponentEmbedding $embedding, ?string $html, string $linkPrefix = '')`

Purpose: Extracts all <a> tags from HTML content and adds them to the embedding's link metadata.

When to use: When content contains HTML with embedded links that should be tracked separately (e.g., biographical text with social media links, articles with reference links).

Parameters:

Features:

Usage:

// Basic usage - extract links from HTML
ComponentEmbedding::extractAndAddLinksFromHtml($ret, $htmlContent);

// With prefix for context (recommended when looping through items)
foreach ($persons as $person) {
    $name = $person->name;
    $bio = $person->bio; // Contains <a href="...">Twitter</a>, <a href="...">LinkedIn</a>

    // Prefix links with person name: "John Doe Twitter", "John Doe LinkedIn"
    ComponentEmbedding::extractAndAddLinksFromHtml($ret, $bio, $name);

    // Clean HTML after extracting links
    $cleanBio = ComponentEmbedding::stripAllHtmlFromText($bio);
    $ret->addSection("Name: $name\nBio: $cleanBio", 'Person');
}

Why use linkPrefix:

Without prefix, 20 people with Twitter links produces 20 identical "Twitter" entries. With prefix, you get "Chris Haas Twitter", "Jane Smith Twitter", etc., providing essential context.

Important: Call extractAndAddLinksFromHtml() BEFORE stripAllHtmlFromText() to preserve the links before HTML is removed.

HTML Cleaning Utility

`stripAllHtmlFromText(?string $text, bool $preserveLists = false)`

CRITICAL: Always use this for user-entered HTML content

Features:

Usage:

// DO THIS:
$cleanCopy = ComponentEmbedding::stripAllHtmlFromText($copy);
$ret->addSection($cleanCopy);

// NOT THIS:
$ret->addSection($copy); // May contain <div>, <p>, <br> tags

Best Practices

1. Avoid Loading Sub-Components

VERY IMPORTANT: Write extraction code directly in getEmbedding(). Do NOT load sub-components.

Strongly Preferred:

public function getEmbedding(): ?ComponentEmbeddingInterface
{
    $ret = ComponentEmbedding::fromComponent($this);

    // Write code directly - NO sub-component loading
    while (have_rows('items')) {
        the_row();
        $ret->addSection(get_sub_field('copy'));
    }

    return $ret;
}

Avoid:

// DON'T load sub-components during embedding
vendi_load_component_v3(['parent', 'child']);

Why: The system hasn't found a good pattern for sub-component loading in embeddings yet. Keep it simple and direct.

2. Always Clean HTML from User Content

// CORRECT:
$cleanCopy = ComponentEmbedding::stripAllHtmlFromText($copy);
$ret->addSection($cleanCopy);

// WRONG:
$ret->addSection($copy); // HTML tags leak into embedding

5. Use Structured Content with Labels

Makes content more parseable by the RAG system:

$contentParts = [];

if ($heading) {
    $contentParts[] = 'Heading: ' . $heading;
}

if ($subheading) {
    $contentParts[] = 'Subheading: ' . $subheading;
}

if ($copy) {
    $contentParts[] = 'Body: ' . ComponentEmbedding::stripAllHtmlFromText($copy);
}

if ($link) {
    $contentParts[] = 'Link: ' . $link['title'];
}

$ret->addSection(implode(PHP_EOL, $contentParts));

Implementation Checklist

Step 1: Inspect Template File

Step 2: Class File Changes

```php

use Vendi\Theme\ComponentInterfaces\ComponentEmbeddingAwareInterface;

use Vendi\Theme\DTO\Embedding\ComponentEmbedding;

use Vendi\Theme\DTO\Embedding\ComponentEmbeddingInterface;

```

```php

use Vendi\Theme\ComponentInterfaces\PrimaryHeadingInterface;

```

```php

use Vendi\Theme\ComponentInterfaces\PrimaryCopyInterface;

```

Step 3: Template File Changes

```php

use Vendi\Theme\Enums\RenderingContextEnum;

```

```php

if (defined('VENDI_RENDER_CONTEXT') && VENDI_RENDER_CONTEXT === RenderingContextEnum::EMBEDDING->value) {

return $component;

}

```

Step 4: getEmbedding() Implementation

For Skippable Components Only

```php

use Vendi\Theme\ComponentInterfaces\ComponentEmbeddingSkipAwareInterface;

```


Testing

After implementation, test with the CLI command:

wp vendi embedding:generate

This command:

  1. Iterates through all published posts/pages
  2. Sets VENDI_RENDER_CONTEXT to EMBEDDING
  3. Loads each component
  4. Calls getEmbedding() on embeddable components
  5. Outputs structured JSON for Qdrant

Verify Output

Check the JSON output for:

Sample Output Format

{
  "content": "Heading: Research Topics\nSection 1: AANA's Current Priorities\nWhat are healthcare executives' perceptions...",
  "metadata": {
    "type": "page",
    "url": "https://example.com/page/",
    "created": "2022-11-29T21:01:08+00:00",
    "updated": "2024-03-07T09:07:06+00:00",
    "component_type": "accordion"
  },
  "id": "660-2"
}

Common Pitfalls

  1. Forgetting to clean HTML: Always use stripAllHtmlFromText() on user content
  2. Loading sub-components: Write extraction code directly in getEmbedding()
  3. Missing template boilerplate: Component will render HTML instead of being embedded
  4. Not filtering layouts: Process only relevant flexible content layouts
  5. Not validating WP_Post: Check instanceof WP_Post before accessing post fields
  6. Adding empty sections: Filter content before calling addSection()
  7. Forgetting to return component: Template must return $component; in embedding context
  8. Extracting links after stripping HTML: Call extractAndAddLinksFromHtml() BEFORE stripAllHtmlFromText()
  9. Missing link context: Use linkPrefix parameter when looping through items to avoid duplicate generic link text

Reference Examples

Examine these components for real-world patterns:

All located in: vendi-theme-parts/components/[component_name]/[component_name].class.php


Your Role

Guide the user through implementing embedding support for a v3 component:

  1. Read the template file: Inspect the actual .php template to understand structure
  2. Identify top-level content: Determine if component has top-level heading and/or copy (outside loops)
  3. Determine pattern: Is it simple, complex, skippable? Does it have repeaters? Links?
  4. Choose interfaces: Based on template inspection, decide which interfaces to implement
  5. Present implementation plan: Describe changes needed with specific field names from template
  6. Implement changes: Update class and template files
  7. Test: Run wp vendi embedding:generate and verify output

Remember:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.