CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

g14wxz/rag-ingestion-trigger-pipeline

Configures database INSERT triggers that offload document chunking and embedding to Edge Functions.

Quality

94%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

High

Do not use without reviewing

Overview
Quality
Evals
Security
Files

SKILL.mdskills/rag-ingestion-trigger-pipeline/

name:
rag-ingestion-trigger-pipeline
description:
Creates Postgres INSERT triggers that fire Edge Functions for document chunking and embedding generation. Configures the ingestion pipeline from raw document insert to vector storage. Use when building RAG ingestion, embed-on-insert pipelines, database-driven document ingestion, or automated embedding workflows.

Pre-Conditions

  • supabase-mcp-verification tile installed and passing.
  • pgvector-hnsw-index-selection tile installed (vector storage target exists). See that skill for the target vector table schema.
  • edge-function-background-orchestration tile installed (Edge Function runtime available). See that skill for Edge Function deployment patterns.
  • pgvector and pg_net extensions enabled.
  • Caller provides: source document table name, embedding model name, chunk size, and Edge Function endpoint URL.

Execution Phases

Phase 1 — Create Document Source Table

  1. Create or verify the raw document table with columns: id UUID PRIMARY KEY DEFAULT gen_random_uuid(), content TEXT NOT NULL, metadata JSONB DEFAULT '{}', status TEXT DEFAULT 'pending', tenant_id UUID NOT NULL, created_at TIMESTAMPTZ DEFAULT now().
  2. Enable RLS on the table.
  3. HALT if the table cannot be created.

Phase 2 — Create Trigger Function

  1. Create a trigger function that fires on INSERT to the document table.
  2. Use pg_net.http_post() to call the embedding Edge Function.
  3. Pass the new row's id, content, and metadata as the request payload.
  4. Set the row's status to 'processing' via an explicit UPDATE after the pg_net call.
  5. Fire AFTER INSERT to ensure the row is committed before the Edge Function fetches it.
CREATE OR REPLACE FUNCTION trigger_embedding_pipeline()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
  PERFORM pg_net.http_post(
    url := '{EDGE_FUNCTION_URL}',
    body := jsonb_build_object('id', NEW.id, 'content', NEW.content, 'metadata', NEW.metadata),
    headers := '{"Authorization": "Bearer {SERVICE_ROLE_KEY}"}'::jsonb
  );
  UPDATE {table} SET status = 'processing' WHERE id = NEW.id;
  RETURN NULL;
END;
$$;

Phase 3 — Attach Trigger

  1. Create the trigger: CREATE TRIGGER on_document_insert AFTER INSERT ON {table} FOR EACH ROW EXECUTE FUNCTION trigger_embedding_pipeline();.
  2. HALT if trigger creation fails.

Phase 4 — Create Edge Function Skeleton

Scaffold supabase/functions/embed-document/index.ts with the template below. Replace {EMBEDDING_MODEL}, {CHUNK_SIZE}, {VECTOR_TABLE}, and {table} with caller-supplied values. For full deployment patterns, refer to the edge-function-background-orchestration skill.

Tip: Save this template as templates/embed-document.ts in your project and reference it to keep the skill invocation lightweight on repeat use.

import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';

const supabase = createClient(
  Deno.env.get('SUPABASE_URL')!,
  Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
);

serve(async (req) => {
  const { id, content, metadata } = await req.json();

  try {
    const chunkSize = {CHUNK_SIZE};
    const chunks = [];
    for (let i = 0; i < content.length; i += chunkSize) {
      chunks.push(content.slice(i, i + chunkSize));
    }

    const vectors = [];
    for (let idx = 0; idx < chunks.length; idx++) {
      const embeddingRes = await fetch('https://api.openai.com/v1/embeddings', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${Deno.env.get('OPENAI_API_KEY')}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({ model: '{EMBEDDING_MODEL}', input: chunks[idx] }),
      });
      const { data } = await embeddingRes.json();
      vectors.push({ document_id: id, chunk_index: idx, content: chunks[idx], embedding: data[0].embedding, metadata });
    }

    const { error: insertError } = await supabase.from('{VECTOR_TABLE}').insert(vectors);
    if (insertError) throw insertError;

    await supabase.from('{table}').update({ status: 'embedded' }).eq('id', id);
    return new Response(JSON.stringify({ ok: true, chunks: vectors.length }), { status: 200 });
  } catch (err) {
    await supabase.from('{table}').update({ status: 'failed' }).eq('id', id);
    return new Response(JSON.stringify({ error: String(err) }), { status: 500 });
  }
});

Deploy via supabase functions deploy embed-document.

Phase 5 — Apply Migration

  1. Package all SQL into a numbered migration file.
  2. Apply via apply_migration.
  3. HALT on failure.

Verification Report

  1. Insert a test document row and confirm the trigger fires.
  2. Confirm pg_net request appears in net._http_response.
  3. Confirm the Edge Function logs show receipt of the payload.
  4. Confirm vector rows appear in the target table after processing.
  5. Report: trigger name, Edge Function URL, test document ID, vector count, status transitions (pending → processing → embedded / failed).

skills

rag-ingestion-trigger-pipeline

tile.json