Tuning vector database similarity thresholds

A Streamlit tool for Chroma, Qdrant, and pgvector — and the reasoning behind it.


The problem

Most RAG pipelines follow the same pattern. A user submits a question. The system embeds it. A vector database returns the K most similar chunks. Those chunks become the LLM’s context. The LLM generates an answer.

The threshold question sits between retrieval and generation: at what similarity score does a result stop being useful? Below the threshold, chunks are discarded. Above it, they reach the LLM.

The answer is not universal. It depends on the embedding model, the corpus, and the query. A threshold that works for technical documentation may not work for customer support transcripts. You cannot reason about it from first principles. You have to look at actual scores against actual queries.

The flow has seven steps.

  1. A user asks a question.
  2. The system embeds the question with a model such as sentence-transformers, OpenAI, or Cohere.
  3. The system searches the vector database, such as Chroma, Qdrant, or pgvector.
  4. The database returns the top N results with similarity scores.
  5. A threshold decides which scores are high enough. Results at or above the threshold pass on, and results below it are discarded.
  6. The remaining chunks become the context for the language model.
  7. The language model generates the answer that the user sees.

The threshold decision sits between retrieval and generation. Set it too low: noise reaches the LLM. Set it too high: relevant chunks are discarded.

None of the three databases this tool supports provide a UI for this. Chroma and pgvector have no UI at all. Qdrant has a dashboard — it shows collections and runs queries, but it does not let you drag a cutoff and watch results disappear in real time.


What the tool does

  • Connects to a local Chroma directory, a local Qdrant directory, or a PostgreSQL + pgvector instance via DSN
  • Takes a text query, embeds it using a selected sentence-transformers model, and fetches top-N results from the database
  • Normalizes all scores to [0, 1] regardless of which database’s native score format is returned
  • Shows a score distribution histogram and result cards; a slider filters results in real time without re-querying the database

A seed_demo.py script creates a 24-document Chroma collection across five topic categories (tech, science, food, business, nature) for testing without a real collection.


Install and run

The demo code is not public yet. I will publish it soon and add the link here.

The app opens at http://localhost:8501. All configuration is in the sidebar.

Database client imports are lazy — inside the search functions, not at module level. Install only the client for the database you use. Chroma, Qdrant, and pgvector are independent.


A walkthrough

Connecting to your data. Select the DB type and enter the path or DSN. If you don’t know the collection name, click List collections — the app queries the database and shows all available names. This removes the most common first-run friction.

The model selector matters. The embedding model in the sidebar must match the model that was used when the collection was created. A mismatch does not raise an error. It produces scores that look plausible — results with scores between 0.4 and 0.7, no obvious pattern — but they are meaningless. You are measuring distance between vectors that live in different spaces.

Read the histogram before tuning. After the first search, look at the score distribution. If most scores cluster below 0.55, the query is genuinely mismatched to the corpus — the problem is not the threshold, it is the query or the collection. If scores cluster above 0.8, the corpus is tightly focused or the query is very specific.

Drag the threshold. This is the point of the tool. Watch which results disappear as you raise the cutoff. At 0.72, do you lose anything that should have stayed? At 0.65, does noise creep in? The right threshold is where the remaining results are all plausible context for the LLM — and the dropped results are not.

Raise Top-N before lowering the threshold. The slider filters only what was fetched. If you fetched 50 results and most are above 0.7, there is no data below 0.7 to explore. Raise Top-N to 100 or 150 to see the full score range.


Architecture and internals

Session state and the slider

Streamlit re-runs the entire script on every widget interaction. A naive implementation would re-query the database on every slider drag — 100ms to 500ms latency per position, depending on the database and collection size. That makes threshold exploration painful.

The solution is to store results in st.session_state on each Search click and have the slider read from it:

# On Search click:
st.session_state["results"] = run_search(query_vec, cfg)

# On every render (including slider drags):
results = st.session_state.get("results")
threshold = st.slider("Similarity threshold", 0.0, 1.0, 0.5)
render_results(results, threshold)  # in-memory filter

This is the core design decision. The slider is fast because it never touches the database.

The boundary between DB access and display is st.session_state. Everything to the right of that boundary is in-memory filtering.

Model caching

Loading a sentence-transformers model takes 1–3 seconds. The model is cached via @st.cache_resource, keyed on model_name:

@st.cache_resource(show_spinner="Loading embedding model…")
def _load_embedder(model_name: str):
    from sentence_transformers import SentenceTransformer
    return SentenceTransformer(model_name)

The first query loads the model. Subsequent queries reuse the cached instance. If you switch models, a new cached instance is created — the old one stays in memory for the session. On a shared server with multiple concurrent users this adds up; for local use it is fine.

Lazy imports

Chroma, Qdrant, and psycopg2 are imported inside their respective search functions, not at the top of the file:

def _chroma_search(vec, path, collection, n):
    import chromadb  # imported here, not at module level
    client = chromadb.PersistentClient(path=path)
    ...

This means Streamlit can load the sidebar even if chromadb is not installed. The import error only surfaces when you try to run a Chroma search. Python caches the import after the first call, so there is no repeated cost on subsequent searches.

Qdrant and Windows file locks

Qdrant’s local storage uses file locking. On Windows, if the process exits without calling client.close(), the lock file is held and the next attempt to open the same directory fails. The search function wraps the close call in a finally block:

client = QdrantClient(path=path)
try:
    points = client.query_points(collection_name=collection, ...).points
finally:
    client.close()

This is harmless on Linux and macOS but required on Windows.

Stale-settings warning

The app stores a snapshot of the sidebar configuration at search time in st.session_state["cfg_snapshot"]. If you change the database, collection, or model without re-running the search, the results on screen still reflect the old configuration. The app compares current sidebar values against the snapshot and shows a warning banner. This prevents silent mismatches — a common source of confusion when iterating over multiple collections.


Score normalization

Chroma and pgvector return cosine distances. Qdrant returns cosine similarity. Their native ranges are different. A score of 0.7 from Chroma is not the same as 0.7 from Qdrant without normalization.

All three databases use cosine-based metrics but expose them differently. Normalization makes scores comparable across DBs and gives the threshold slider a consistent meaning.

DatabaseWhat the API returnsFormula
ChromaCosine distance [0, 2]score = 1 - distance / 2
QdrantCosine similarity [-1, 1]score = (raw + 1) / 2
pgvectorCosine distance [0, 2] via <=>SQL: (2.0 - (embedding <=> %s)) / 2.0

For pgvector, the normalization happens in the SQL query, not in Python. This avoids fetching a raw distance and post-processing it in the application layer. The <=> operator and the normalization expression are evaluated together in the Postgres query plan.

For Chroma: include=["documents", "distances", "metadatas"] must be passed to col.query() to get scores and text back. The default include=[] returns IDs only — correct for a speed-focused benchmark, but the threshold tuner needs the scores.


Text mode vs Advanced mode

Two query modes exist for one reason: embedding model alignment.

Text mode — use when the collection was embedded with one of the six listed sentence-transformers models. The app embeds the query using the model selected in the sidebar, L2-normalizes it, and runs the search. The model must match the collection’s ingestion model.

Advanced mode — use when the collection was embedded with OpenAI, Cohere, or any provider not in the sidebar, or when the vector dimension doesn’t match any listed model. Paste the embedding as comma-separated floats.

To get an OpenAI embedding:

import openai
vec = openai.OpenAI().embeddings.create(
    model="text-embedding-3-small",
    input="your query text"
).data[0].embedding
print(",".join(str(x) for x in vec))

The app L2-normalizes the pasted vector before searching. Advanced mode bypasses sentence-transformers entirely. The DB client library is still required.


Interpreting scores

The color bands in the result cards (green ≥ 0.72, orange ≥ 0.58, red < 0.58) are defaults. They are not universal thresholds.

Three factors shift where the useful boundary falls:

Model size. Larger models (768 dims, e.g. all-mpnet-base-v2) tend to produce higher similarity scores for genuinely related content than smaller models (384 dims, e.g. all-MiniLM-L6-v2). A 0.70 from a small model may be equivalent to a 0.78 from a large model.

Corpus focus. A collection covering a narrow topic will cluster scores higher than a diverse general-purpose collection. The histogram tells you this before you touch the slider.

Query specificity. A specific factual question produces a sharper gap between relevant and irrelevant results than a vague phrase. Vague queries have flatter score distributions.

The practical approach: run 5–10 representative queries from your actual use case. Note where the relevant/irrelevant boundary falls each time. The threshold you want is the value that keeps the true positives and loses the noise — consistently, across those queries.