similarity-search-patterns

similarity-search-patterns is a skill for Claude Code from EngineerWithAI/engineerwith-agents. It costs 30 tokens per session (3,758 once invoked), scanned A, a copy of similarity-search-patterns, MIT.

A guide to finding items with similar meaning by storing text as numerical representations in vector databases. It covers methods for comparing these representations and retrieving nearby results.

In plain words
What is it for?
Use it for semantic search, document retrieval, recommendation systems, and retrieval-augmented generation (RAG), where an AI model looks up relevant information before answering.
Why use it?
It helps build searches that understand the meaning of a query, not just matching the same words, while addressing speed and scale concerns.

Skill for Claude Code

Written for Claude Code: shipped in a Claude Code plugin. Also seen: positional $N argument.

Part of the llm-application-dev plugin — 8 skills shipped together

Good fit Use it for semantic search, document retrieval, recommendation systems, and retrieval-augmented generation (RAG), where an AI model looks up relevant information before answering.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/engineerwithai/engineerwith-agents/similarity-search-patterns
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add EngineerWithAI/engineerwith-agents --skill similarity-search-patterns
Clone the repo
git clone --depth 1 https://github.com/EngineerWithAI/engineerwith-agents

Made for: Claude Code.

Or install llm-application-dev, the plugin that ships this one along with the rest of its 8 skills.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for similarity-search-patterns

README.md
[![agentmods](https://agentmods.dev/badge/skills/engineerwithai/engineerwith-agents/similarity-search-patterns.svg)](https://agentmods.dev/skills/engineerwithai/engineerwith-agents/similarity-search-patterns)
Your own site
<a href="https://agentmods.dev/skills/engineerwithai/engineerwith-agents/similarity-search-patterns"><img src="https://agentmods.dev/badge/skills/engineerwithai/engineerwith-agents/similarity-search-patterns.svg" alt="Measured on agentmods" height="20"></a>
Per session 30 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 3,758 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. A grade says what 26 rules found in the file — not that it is safe.
Origin 100% copy Near-identical to another mod in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00030 $0.03758
Opus 5 $0.00015 $0.01879
Sonnet 5 $0.00006 $0.00752
Haiku 4.5 $0.00003 $0.00376

Measured 4d ago against content hash be2052f62914, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-07, from the pricing page.

Security

Grade A, and why

similarity-search-patterns scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

rows = await conn.fetch(query, *params)
Origin

This is a copy

100% identical to similarity-search-patterns — 0 lines differ, which has more behind it and is treated as the original. This page carries a canonical link to it rather than competing with it.

plugins/llm-application-dev/skills/similarity-search-patterns/SKILL.md · 559 lines

How it starts

The opening of the file, as written. The whole thing — 559 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Similarity Search Patterns

Patterns for implementing efficient similarity search in production systems.

When to Use This Skill

  • Building semantic search systems
  • Implementing RAG retrieval
  • Creating recommendation engines
  • Optimizing search latency
  • Scaling to millions of vectors
  • Combining semantic and keyword search

Core Concepts

1. Distance Metrics

Metric Formula Best For
Cosine 1 - (A·B)/(‖A‖‖B‖) Normalized embeddings
Euclidean (L2) √Σ(a-b)² Raw embeddings
Dot Product A·B Magnitude matters
Manhattan (L1) Σ a-b

2. Index Types

┌─────────────────────────────────────────────────┐
│                 Index Types                      │
├─────────────┬───────────────┬───────────────────┤
│    Flat     │     HNSW      │    IVF+PQ         │
│ (Exact)     │ (Graph-based) │ (Quantized)       │
├─────────────┼───────────────┼───────────────────┤
│ O(n) search │ O(log n)      │ O(√n)             │
│ 100% recall │ ~95-99%       │ ~90-95%           │
│ Small data  │ Medium-Large  │ Very Large        │
└─────────────┴───────────────┴───────────────────┘

Templates

Template 1: Pinecone Implementation

from pinecone import Pinecone, ServerlessSpec
from typing import List, Dict, Optional
import hashlib

class PineconeVectorStore:
    def __init__(
        self,
        api_key: str,
        index_name: str,
        dimension: int = 1536,
        metric: str = "cosine"
    ):
        self.pc = Pinecone(api_key=api_key)

        # Create index if not exists
        if index_name not in self.pc.list_indexes().names():
            self.pc.create_index(
                name=index_name,
                dimension=dimension,
                metric=metric,
                spec=ServerlessSpec(cloud="aws", region="us-east-1")
            )

        self.index = self.pc.Index(index_name)

    def upsert(
        self,
        vectors: List[Dict],
        namespace: str = ""
    ) -> int:
        """
        Upsert vectors.
        vectors: [{"id": str, "values": List[float], "metadata": dict}]
        """
        # Batch upsert
        batch_size = 100
        total = 0

        for i in range(0, len(vectors), batch_size):
            batch = vectors[i:i + batch_size]
            self.index.upsert(vectors=batch, namespace=namespace)
            total += len(batch)

        return total

    def search(
        self,
        query_vector: List[float],
        top_k: int = 10,
        namespace: str = "",
        filter: Optional[Dict] = None,
        include_metadata: bool = True
    ) -> List[Dict]:
        """Search for similar vectors."""
        results = self.index.query(
            vector=query_vector,
            top_k=top_k,
            namespace=namespace,
            filter=filter,
            include_metadata=include_metadata
        )

        return [
            {
                "id": match.id,
                "score": match.score,
                "metadata": match.metadata
            }
            for match in results.matches
        ]

    def search_with_rerank(
        self,
        query: str,
        query_vector: List[float],
        top_k: int = 10,
        rerank_top_n: int = 50,
        namespace: str = ""
    ) -> List[Dict]:
        """Search and rerank results."""
        # Over-fetch for reranking
        initial_results = self.search(
            query_vector,
            top_k=rerank_top_n,
            namespace=namespace
        )

        # Rerank with cross-encoder or LLM
        reranked = self._rerank(query, initial_results)

        return reranked[:top_k]

    def _rerank(self, query: str, results: List[Dict]) -> List[Dict]:
        """Rerank results using cross-encoder."""
        from sentence_transformers import CrossEncoder

        model = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')

        pairs = [(query, r["metadata"]["text"]) for r in results]
        scores = model.predict(pairs)

        for result, score in zip(results, scores):
            result["rerank_score"] = float(score)

        return sorted(results, key=lambda x: x["rerank_score"], reverse=True)

    def delete(self, ids: List[str], namespace: str = ""):
        """Delete vectors by ID."""
        self.index.delete(ids=ids, namespace=namespace)

    def delete_by_filter(self, filter: Dict, namespace: str = ""):
        """Delete vectors matching filter."""
        self.index.delete(filter=filter, namespace=namespace)

Read the full file on GitHub · 559 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 559 lines · 30 tokens per session scan A be2052f62914

Subscribe to this mod's changes

similarity-search-patterns is a skill published in the GitHub repository EngineerWithAI/engineerwith-agents (4 stars, last pushed 7mo ago), licensed MIT. It adds 30 tokens to every session and 3,758 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 1 finding (makes network calls). It is 100% identical to similarity-search-patterns, differing in 0 lines, and is treated as a copy.