# pgEdge Vectorizer **RuDB integration:** PostgreSQL 19 in-tree runtime and initdb bootstrap. [![License](https://img.shields.io/badge/License-PostgreSQL-blue.svg)](LICENCE.md) A PostgreSQL extension for asynchronous text chunking and vector embedding generation. ## Overview pgEdge Vectorizer automatically chunks text content and generates vector embeddings using background workers. It supports multiple embedding providers (OpenAI, Voyage AI, and Ollama) and provides a simple SQL interface for enabling vectorization on any table. ### Key Features - **Automatic Chunking**: Intelligently splits text into chunks with configurable strategies - **Async Processing**: Background workers process embeddings without blocking your application - **Multiple Providers**: Support for OpenAI, Voyage AI, and Ollama (local embeddings) - **Configurable**: Extensive GUC parameters for fine-tuning behavior - **Batching**: Efficient batch processing of embeddings - **Retry Logic**: Automatic retry with exponential backoff for failed embeddings - **Monitoring**: Built-in views and functions for monitoring queue status ## Requirements - RuDB PostgreSQL 19 from this source tree - libcurl support in the RuDB build - API key for OpenAI or Voyage AI providers; Ollama does not require one ## Installation in RuDB PostgreSQL 19 Vectorizer is integrated into the RuDB server and initialized during `initdb`. Do not build it as a separate extension, add it to `shared_preload_libraries`, or run `CREATE EXTENSION pgedge_vectorizer`. Build and install RuDB using the repository-level build instructions. Configure the runtime in `postgresql.conf`: ```ini rudb_ai.databases = 'mydb' rudb_ai.provider = 'openai' rudb_ai.api_key_file = '~/.pgedge-vectorizer-llm-api-key' rudb_ai.model = 'text-embedding-3-small' rudb_ai.num_workers = 2 rudb_ai.batch_size = 10 rudb_ai.default_chunk_size = 400 rudb_ai.default_chunk_overlap = 50 ``` After changing startup-sensitive settings, restart RuDB. The `pgedge_vectorizer` schema and its queue/functions are created by RuDB bootstrap on a fresh cluster. ## Quick Start ### Example: Vectorize a Documents Table ```sql -- Create a documents table CREATE TABLE articles ( id BIGSERIAL PRIMARY KEY, title TEXT, content TEXT, url TEXT, created_at TIMESTAMPTZ DEFAULT NOW() ); -- Enable vectorization on the content column SELECT pgedge_vectorizer.enable_vectorization( source_table := 'articles', source_column := 'content', chunk_strategy := 'token_based', chunk_size := 400, chunk_overlap := 50 ); -- Insert a document - it will be automatically chunked and vectorized INSERT INTO articles (title, content, url) VALUES ( 'Introduction to PostgreSQL', 'PostgreSQL is a powerful, open source object-relational database system...', 'https://example.com/postgres-intro' ); -- Check queue status SELECT * FROM pgedge_vectorizer.queue_status; -- Wait for background workers to process... -- Query for similar content SELECT a.title, c.content, c.embedding <=> '[0.1, 0.2, ...]'::vector AS distance FROM articles a JOIN articles_content_chunks c ON a.id = c.source_id ORDER BY distance LIMIT 5; ``` ## Configuration Parameters All configuration parameters can be set in `postgresql.conf` or via `ALTER SYSTEM`. ### Provider Configuration | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `rudb_ai.provider` | string | `'openai'` | Embedding provider (openai, voyage, ollama) | | `rudb_ai.api_key_file` | string | `'~/.pgedge-vectorizer-llm-api-key'` | Path to API key file | | `rudb_ai.api_url` | string | `'https://api.openai.com/v1'` | API endpoint URL | | `rudb_ai.model` | string | `'text-embedding-3-small'` | Embedding model name | ### Worker Configuration | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `rudb_ai.num_workers` | integer | `2` | Number of background workers (requires restart) | | `rudb_ai.batch_size` | integer | `10` | Batch size for embedding generation | | `rudb_ai.max_retries` | integer | `3` | Maximum retry attempts for failed embeddings | | `rudb_ai.worker_poll_interval` | integer | `1000` | Worker polling interval in milliseconds | ### Chunking Configuration | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `rudb_ai.auto_chunk` | boolean | `true` | Enable automatic chunking | | `rudb_ai.default_chunk_strategy` | string | `'token_based'` | Default chunking strategy | | `rudb_ai.default_chunk_size` | integer | `400` | Default chunk size in tokens | | `rudb_ai.default_chunk_overlap` | integer | `50` | Default chunk overlap in tokens | ### Queue Management | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `rudb_ai.auto_cleanup_hours` | integer | `24` | Automatically delete completed queue items older than this many hours. Set to 0 to disable automatic cleanup. | ## SQL API Reference ### Functions #### `enable_vectorization()` Enable automatic vectorization for a table column. ```sql SELECT pgedge_vectorizer.enable_vectorization( source_table REGCLASS, source_column NAME, chunk_strategy TEXT DEFAULT NULL, chunk_size INT DEFAULT NULL, chunk_overlap INT DEFAULT NULL, embedding_dimension INT DEFAULT 1536, chunk_table_name TEXT DEFAULT NULL ); ``` #### `disable_vectorization()` Disable vectorization for a table. ```sql SELECT pgedge_vectorizer.disable_vectorization( source_table REGCLASS, drop_chunk_table BOOLEAN DEFAULT FALSE ); ``` #### `chunk_text()` Manually chunk text. ```sql SELECT pgedge_vectorizer.chunk_text( content TEXT, strategy TEXT DEFAULT NULL, chunk_size INT DEFAULT NULL, overlap INT DEFAULT NULL ); ``` #### `retry_failed()` Retry failed queue items. ```sql SELECT pgedge_vectorizer.retry_failed( max_age_hours INT DEFAULT 24 ); ``` #### `clear_completed()` Remove old completed items from the queue. ```sql SELECT pgedge_vectorizer.clear_completed( older_than_hours INT DEFAULT 24 ); ``` **Note:** Workers automatically clean up completed items based on `rudb_ai.auto_cleanup_hours` (default 24 hours). Manual cleanup is only needed if you want to clean up more frequently or if automatic cleanup is disabled (set to 0). #### `show_config()` Show all configuration settings. ```sql SELECT * FROM pgedge_vectorizer.show_config(); ``` ### Views #### `queue_status` Summary of queue items by table and status. ```sql SELECT * FROM pgedge_vectorizer.queue_status; ``` #### `failed_items` Failed queue items with error details. ```sql SELECT * FROM pgedge_vectorizer.failed_items; ``` #### `pending_count` Count of pending items. ```sql SELECT * FROM pgedge_vectorizer.pending_count; ``` ## Architecture ### Components 1. **Triggers**: Automatically detect changes to configured columns 2. **Chunking Engine**: Splits text into optimal-sized chunks 3. **Queue Table**: Stores pending embedding tasks 4. **Background Workers**: Process queue items asynchronously 5. **Provider Interface**: Abstraction layer for different embedding APIs 6. **Chunk Tables**: Store chunks and their embeddings ### Processing Flow ``` INSERT/UPDATE → Trigger → Chunk Text → Insert Chunks → Queue Items ↓ Background Worker ↓ Generate Embeddings ↓ Update Chunk Tables ``` ## Monitoring ### Check Queue Status ```sql -- Overall status SELECT * FROM pgedge_vectorizer.queue_status; -- Pending items SELECT * FROM pgedge_vectorizer.pending_count; -- Failed items SELECT * FROM pgedge_vectorizer.failed_items; ``` ### Check Configuration ```sql SELECT * FROM pgedge_vectorizer.show_config(); ``` ### Manual Queue Inspection ```sql SELECT id, chunk_table, status, attempts, error_message, created_at FROM pgedge_vectorizer.queue WHERE status = 'failed' ORDER BY created_at DESC LIMIT 10; ``` ## Troubleshooting ### Workers Not Starting Vectorizer workers are registered by the RuDB server. Check the configured database list and effective settings: ```sql SHOW rudb_ai.databases; SELECT * FROM pgedge_vectorizer.show_config(); ``` An empty `rudb_ai.databases` list leaves workers idle. Also check RuDB server logs and API-key file permissions. ### Embeddings Not Generated 1. Verify provider/model configuration and API-key access. 2. Check `pgedge_vectorizer.failed_items`. 3. Retry failed queue entries with `pgedge_vectorizer.retry_failed()`. ## Performance Tips 1. **Batch Size**: Larger batches (10-50) are more efficient for API calls 2. **Worker Count**: Match to your API rate limits and server capacity 3. **Chunk Size**: 200-500 tokens is optimal for most use cases 4. **Overlap**: 10-20% overlap provides good context without too much duplication ## Development Vectorizer is developed and tested as part of the RuDB PostgreSQL 19 tree. Use the repository-level build procedure in `README_BUILD.txt` and the canonical validation runbook. Regression coverage lives under `src/test/modules/vectorizer`; vector index regression/TAP coverage lives under `src/test/modules/vector`. The release gate uses the integrated PostgreSQL build and test infrastructure rather than the upstream standalone PG14-18 CI matrix. ## Roadmap - [x] Support for Voyage AI embedding models - [x] Support for Ollama (local models) - [ ] Semantic chunking strategy - [ ] Markdown-aware chunking - [ ] Sentence-based chunking - [ ] Integration with tiktoken for accurate token counting - [ ] Cost tracking and quotas - [ ] Multi-database support - [ ] Custom embedding dimensions - [ ] Webhook notifications ## License PostgreSQL License (see LICENCE.md) ## Contributing In RuDB, Vectorizer changes follow the repository-level development and review workflow rather than the standalone pgEdge contribution/CI policy. Quick checklist: - Run the integrated PostgreSQL/vectorizer test gates. - Follow PostgreSQL coding conventions. - Add regression coverage for behavior changes. - Update the RuDB-integrated documentation when interfaces change. ## Support For issues and questions: - **GitHub**: https://github.com/pgEdge/pgedge-vectorizer - **Issues**: https://github.com/pgEdge/pgedge-vectorizer/issues - **Documentation**: https://github.com/pgEdge/pgedge-vectorizer/blob/main/docs/index.md ## Credits Developed by pgEdge, Inc. Copyright (c) 2025 - 2026, pgEdge, Inc.