Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计提醒

vector-search矢量搜索

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

196

周安装

8

GitHub Stars

1

下载量

63
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:vector-search(矢量搜索)
来源仓库:https://github.com/cleanexpo/nodejs-starter-v1
仓库路径:skills/vector-search
安装命令:
npx skills add https://github.com/cleanexpo/nodejs-starter-v1 --skill vector-search
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/cleanexpo/nodejs-starter-v1 --skill vector-search

简介

vector-search 基于 pgvector 实现嵌入查询与相似性搜索,支持记忆库与 RAG 双系统。

  • 适用于知识问答、文档检索或个性化推荐等需要语义匹配的应用场景。
  • 集成多提供商嵌入抽象、混合评分与分块策略,优化召回与精度平衡。
  • 使用前请确认 PostgreSQL 已安装 pgvector 扩展并配置合适索引策略。
  • 建议定期评估向量维度与相似度阈值,避免搜索结果不相关或性能下降。

SKILL.md

Vector Search - Embedding Queries & Similarity Search

Codifies the project's dual vector search systems (Memory Store for agent domain knowledge, RAG Pipeline for document retrieval), the multi-provider embedding abstraction, pgvector indexing, hybrid search scoring, and chunking strategies. All patterns are built on Supabase/PostgreSQL with pgvector.

Description

Codifies pgvector embedding queries, similarity search, hybrid search, and multi-provider embedding generation for NodeJS-Starter-V1's Supabase/PostgreSQL stack, covering the Memory Store and RAG Pipeline vector infrastructure, indexing strategies, and chunking patterns.


When to Apply

Positive Triggers

  • Adding semantic search to new data types
  • Creating or modifying embedding generation logic
  • Implementing similarity queries or nearest-neighbour lookups
  • Configuring chunking strategies for document ingestion
  • Tuning search relevance (thresholds, weights, reranking)
  • Adding new embedding providers
  • User mentions: "vector", "embedding", "semantic search", "similarity", "RAG", "pgvector", "cosine"

Negative Triggers

  • Building dashboard UI for search results (use dashboard-patterns instead)
  • Adding full-text keyword search only (use PostgreSQL tsvector directly)
  • Instrumenting search latency metrics (use metrics-collector instead)
  • Logging search queries (use structured-logging instead)

Core Directives

The Three Laws of Vector Search

  1. Provider-agnostic: All embedding generation goes through EmbeddingProvider abstraction. Never call OpenAI/Ollama directly.
  2. Hybrid by default: Combine vector similarity with keyword matching. Pure vector search misses exact terms; pure keyword misses semantics.
  3. Server-side scoring: Similarity computation happens in PostgreSQL via RPC functions. Never download all vectors to Python for client-side comparison.

Existing Project Infrastructure

Two Vector Search Systems

SystemLocationPurposeTable
Memory Storesrc/memory/store.pyAgent domain knowledge (patterns, preferences, debugging)domain_memories
RAG Pipelinesrc/rag/storage.pyDocument retrieval (uploaded docs, chunked content)document_chunks

Both share the same EmbeddingProvider abstraction from src/memory/embeddings.py.

Embedding Providers

ProviderModelDimensionsUse Case
OpenAItext-embedding-3-small1536Production (preferred)
Ollamanomic-embed-text768Local development (free)
SimpleHash-based1536Testing only (deterministic)

Selection via get_embedding_provider() — checks OPENAI_API_KEY, then ANTHROPIC_API_KEY, then falls back to SimpleEmbeddingProvider.

API Routes

RouteMethodSearch Type
/rag/searchPOSTVector, hybrid, or keyword
/rag/uploadPOSTDocument ingestion + embedding
/api/searchPOSTFull-text search (tsvector only)

Database

TableVector ColumnIndex TypeDistance Function
documentsVECTOR(1536)IVFFlatvector_cosine_ops
domain_memoriesembeddingCosine (via RPC)
document_chunksembeddingCosine (via RPC)

Embedding Provider Pattern

The EmbeddingProvider abstract base class defines a single method:

class EmbeddingProvider(ABC):
    @abstractmethod
    async def get_embedding(self, text: str) -> list[float]:
        """Generate embedding vector for text."""
        pass

Three implementations: OpenAIEmbeddingProvider (calls /v1/embeddings via httpx), OllamaEmbeddingProvider (local /api/embeddings), SimpleEmbeddingProvider (hash-based, testing only).

Adding a New Provider

  1. Subclass EmbeddingProvider
  2. Implement get_embedding() returning a fixed-dimension vector
  3. Add selection logic in get_embedding_provider()
  4. Match the dimension to existing index (1536 for OpenAI compatibility, or create a separate index)

Dimension Consistency Rule

All vectors in a table MUST share the same dimension. If mixing providers with different dimensions (e.g., OpenAI 1536 vs Ollama 768), either:

  • Pad/truncate to a standard dimension, OR
  • Use separate columns per dimension, OR
  • Standardise on one dimension and re-embed when switching providers

The project currently standardises on 1536 dimensions (OpenAI).


Search Patterns

Similarity Search (Memory Store)

MemoryStore.find_similar() generates a query embedding and calls the find_similar_memories PostgreSQL RPC:

async def find_similar(self, query_text: str, domain: MemoryDomain | None = None,
    user_id: str | None = None, similarity_threshold: float = 0.7, limit: int = 10,
) -> list[dict[str, Any]]:
    query_embedding = await self.embedding_provider.get_embedding(query_text)
    result = self.client.rpc("find_similar_memories", {
        "query_embedding": json.dumps(query_embedding),
        "match_threshold": similarity_threshold,
        "match_count": limit,
        "filter_domain": domain.value if domain else None,
        "filter_user_id": user_id,
    }).execute()
    return result.data or []

Key parameters: match_threshold (0.0–1.0, cosine similarity minimum), match_count (max results). Domain and user filters are applied server-side in the RPC function.

Hybrid Search (RAG Pipeline)

RAGStore.hybrid_search() combines vector similarity with keyword matching using configurable weights:

async def hybrid_search(self, query: str, project_id: str,
    vector_weight: float = 0.6, keyword_weight: float = 0.4,
    limit: int = 10, threshold: float = 0.5,
) -> list[dict[str, Any]]:
    query_embedding = await self.embedding_provider.get_embedding(query)
    result = self.client.rpc("hybrid_search", {
        "query_text": query,
        "query_embedding": query_embedding,
        "project_id_filter": project_id,
        "vector_weight": vector_weight,
        "keyword_weight": keyword_weight,
        "match_threshold": threshold,
        "match_count": limit,
    }).execute()
    return result.data or []

Default weights: 60% vector + 40% keyword. Adjust for domain:

  • Technical docs: 70/30 (semantics matter more)
  • Exact match scenarios (IDs, codes): 30/70 (keywords matter more)
  • General content: 60/40 (balanced)

Full-Text Search (PostgreSQL tsvector)

The /api/search route uses native PostgreSQL full-text search with ts_rank:

func.ts_rank(
    func.to_tsvector("english", Document.title + " " + Document.content),
    func.plainto_tsquery("english", query_text),
    32,  # RANK_CD normalisation flag
).label("relevance")

This is independent of vector search and uses the documents table directly via SQLAlchemy.


Indexing Patterns

IVFFlat Index (Current)

The project uses IVFFlat for approximate nearest-neighbour search:

CREATE INDEX idx_documents_embedding
  ON documents USING ivfflat (embedding vector_cosine_ops);

IVFFlat partitions vectors into lists (clusters). Query searches only the nearest cluster(s), trading recall for speed.

Tuning parameters:

  • lists (build-time): Number of clusters. Rule of thumb: sqrt(row_count) for < 1M rows
  • probes (query-time): Number of clusters to search. Higher = better recall, slower. Default: 1
-- Set probes for a session (higher = more accurate, slower)
SET ivfflat.probes = 10;

HNSW Index (Recommended for Production)

For datasets > 10K rows, prefer HNSW (Hierarchical Navigable Small World):

CREATE INDEX idx_documents_embedding_hnsw
  ON documents USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

HNSW provides better recall than IVFFlat without manual tuning. Higher m and ef_construction improve quality at the cost of build time and memory.

Distance Functions

FunctionOperatorIndex OpsUse When
Cosine similarity<=>vector_cosine_opsNormalised embeddings (most common)
L2 distance<->vector_l2_opsRaw distance comparison
Inner product<#>vector_ip_opsPre-normalised, performance-critical

The project uses cosine similarity (vector_cosine_ops) throughout.


Chunking Strategies

The RAG pipeline supports five chunking strategies via ChunkingStrategy enum:

StrategyWhen to UseConfig
FIXED_SIZEUniform chunks, simple contentchunk_size=512, chunk_overlap=50
SEMANTICRespects paragraph/section boundariesSame + boundary detection
RECURSIVENested structure (Markdown, HTML)Splits by headers, then paragraphs, then sentences
PARENT_CHILDBest recall with contextparent_chunk_size=2048, child chunk_size=512
CODE_AWARESource code filesSplits by functions/classes

Default: PARENT_CHILD with 512-token children and 2048-token parents. Search matches children; context retrieval includes the parent chunk.

Pipeline Config

PipelineConfig(
    chunking_strategy=ChunkingStrategy.PARENT_CHILD,
    chunk_size=512,
    chunk_overlap=50,
    parent_chunk_size=2048,
    generate_embeddings=True,
    generate_keywords=True,
)

Relevance & Scoring

Threshold Guidelines

ThresholdMeaningUse Case
0.9+Near-exact semantic matchDeduplication
0.7–0.9Strong relevanceDefault search
0.5–0.7Moderate relevanceExploratory search
< 0.5Weak matchUsually noise

The Memory Store defaults to similarity_threshold=0.7. The RAG Pipeline defaults to min_score=0.5.

Relevance Decay

MemoryStore.update_relevance() adjusts memory relevance based on feedback:

  • Positive feedback (+0.1 per point, capped at 1.0)
  • Negative feedback (configurable decay_rate, default 0.1, floored at 0.0)

Stale Memory Pruning

MemoryStore.prune_stale() removes memories below min_relevance=0.3 or older than max_age_days=90 via the prune_stale_memories RPC.


Pydantic Models

Memory System

ModelFieldsPurpose
MemoryEntrydomain, category, key, value, embedding, relevance_score, access_countCore memory unit
MemoryQuerydomain, category, query_text, similarity_threshold, tags, limit, offsetQuery specification
MemoryResultentries, total_count, queryPaginated result
MemoryDomainKNOWLEDGE, PREFERENCE, TESTING, DEBUGGINGDomain enum

RAG System

ModelFieldsPurpose
DocumentChunksource_id, content, embedding, chunk_level, heading_hierarchy, keywordsChunk record
DocumentSourcesource_type, source_uri, status, metadataSource tracking
SearchRequestquery, project_id, search_type, vector_weight, keyword_weight, min_scoreSearch input
SearchResultchunk_id, content, vector_score, keyword_score, combined_scoreResult item
SearchResponseresults, total_count, search_type, execution_time_msSearch output

Database Schema

documents Table (Legacy)

CREATE TABLE documents (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  title VARCHAR(500) NOT NULL,
  content TEXT NOT NULL,
  embedding VECTOR(1536),
  -- ... other columns
);
CREATE INDEX idx_documents_embedding ON documents USING ivfflat (embedding vector_cosine_ops);

domain_memories Table

Stores agent memories with embeddings for semantic retrieval. Accessed via MemoryStore class.

document_chunks Table

Stores RAG pipeline chunks with embeddings. Accessed via RAGStore class. Includes heading_hierarchy, summary, entities, keywords, and classification_tags for enriched retrieval.

RPC Functions

FunctionPurpose
find_similar_memoriesCosine similarity search on domain_memories with domain/user filters
hybrid_searchCombined vector + keyword search on document_chunks
prune_stale_memoriesDelete low-relevance or expired memories
increment_memory_accessIncrement access count on retrieval

Anti-Patterns

Anti-PatternWhy It FailsCorrect Approach
Client-side similarity computationDownloads all vectors, O(n) per query, no index usagePostgreSQL RPC with pgvector index
Mixing embedding dimensions in one columnVECTOR(1536) rejects 768-dim vectorsStandardise dimension or use separate columns
No similarity thresholdReturns noise matches below 0.3Always set match_threshold (0.5–0.7)
Embedding at query time without cachingRe-embeds identical queriesCache query embeddings for repeated searches
IVFFlat with probes=1 on large datasetsPoor recall (misses relevant results)Increase probes or migrate to HNSW
Storing embeddings without indexingSequential scan on every queryCreate IVFFlat or HNSW index
Hardcoding OpenAI API callsBreaks local development, vendor lock-inUse EmbeddingProvider abstraction
Chunking without overlapLoses context at chunk boundariesSet chunk_overlap=50 minimum

Checklist for New Vector Search Features

Embedding

  • Uses EmbeddingProvider abstraction (never direct API calls)
  • Dimension matches existing index (1536 default)
  • Handles provider unavailability (fallback or graceful error)

Search

  • Hybrid search by default (vector + keyword)
  • Similarity threshold configured (not unbounded)
  • Server-side computation via PostgreSQL RPC
  • Results include similarity scores for transparency

Indexing

  • pgvector index created on embedding column
  • Distance function matches query pattern (cosine for normalised)
  • Index type appropriate for dataset size (IVFFlat < 10K, HNSW >= 10K)

Data Quality

  • Chunking strategy matches content type
  • Chunk overlap prevents boundary information loss
  • Stale/expired entries have pruning mechanism

Integration

  • Search latency instrumented via metrics-collector
  • Errors use error-taxonomy codes
  • Queries logged via structured-logging

Response Format

[AGENT_ACTIVATED]: Vector Search
[PHASE]: {Design | Implementation | Review}
[STATUS]: {in_progress | complete}

{vector search analysis or implementation guidance}

[NEXT_ACTION]: {what to do next}

Integration Points

Council of Logic

  • Turing: Verify search is O(log n) via index, not O(n) sequential scan
  • Shannon: Embedding dimension and chunk size tuned for information density

Metrics Collector

  • search_query_duration_ms histogram for search latency
  • search_result_count gauge for average results per query
  • embedding_generation_duration_ms histogram for provider latency

Structured Logging

  • Debug-level embedding generation logs (model, dimensions, text length)
  • Info-level search execution logs (query, domain, result count)

Error Taxonomy

  • DATA_VECTOR_PROVIDER_UNAVAILABLE (503) — embedding provider down
  • DATA_VECTOR_DIMENSION_MISMATCH (422) — wrong embedding dimension
  • DATA_VECTOR_THRESHOLD_INVALID (422) — threshold out of [0, 1] range

Data Validation

  • SearchRequest validated via Pydantic (query non-empty, threshold in range, limit bounded)
  • PipelineConfig validates chunk sizes and strategy enum

Dashboard Patterns

  • Search results displayed via DataStrip for aggregate metrics
  • Real-time search activity via Supabase Realtime on document_chunks table

Australian Localisation (en-AU)

  • Spelling: neighbour, optimise, normalise, analyse, behaviour, colour
  • Date: ISO 8601 in storage; DD/MM/YYYY in UI display
  • Timezone: AEST/AEDT — timestamps stored as UTC, converted for display

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.41%
按下载量换算21

Claude

28.16%
按下载量换算18

Cursor

18.61%
按下载量换算12

Gemini CLI

10.04%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

可疑

Snyk

可疑

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills