A marketer starts from a list of search keywords with their monthly volumes. A hundred and fifty keywords is too many to read and too few to ignore. The journey view groups them into themes and places each theme on a path from first curiosity to purchase. The grouping is the part I wanted to be boring: the same keywords must produce the same groups every time someone opens the page.
The pipeline

| Stage | What happens | Constant |
|---|---|---|
| Input | Rows the explorer already computed: keyword, volume, intent. Deduplicated, sorted by volume, capped | 150 keywords |
| Embed | One vector per keyword from an embedding model, in batches | 512 per batch |
| Graph | For each keyword, its nearest neighbours by cosine similarity above a floor | Top 5, similarity at least 0.35 |
| Cluster | Label propagation over the graph | At most 40 passes |
| Name | A small model proposes a label per cluster, with a time limit | 20 seconds |
| Stage | Each cluster is placed in a funnel stage by a vote of its keywords | Weighted by volume |
Why not ask a model to group them
The direct approach is to hand the list to a language model and ask for themes. It works, and it has two properties that are wrong for this screen.
It is not stable. The same list gives different groupings on different calls, so a user who returns to the page sees their keywords rearranged. And it cannot be inspected. When a keyword lands in an odd theme there is no reason to look at.
A graph with explicit edges has both properties. An edge exists because two vectors are similar above a stated number, and a cluster exists because of the edges.
The graph
Each keyword is embedded. Vectors are normalised to unit length, so a dot product is the cosine similarity.
For each keyword the code computes its similarity to every other, keeps those at or above the floor of 0.35, sorts them, and takes the top five. The pair is stored as an undirected edge, with the larger weight kept if both ends chose each other.
One line in that function is there only for determinism. When two neighbours have exactly the same similarity, the sort breaks the tie by index.
# similarity descending, ties by index ascending
sims.sort(key=lambda t: (-t[0], t[1]))
for s, j in sims[:top_k]:
a, b = (i, j) if i < j else (j, i)
w = max(0.0, min(1.0, s))
if best.get((a, b), -1.0) < w:
best[(a, b)] = w
The comment is translated from Korean. Without the second sort key, which neighbour makes the cut at position five would depend on the order the sort happened to leave equal elements in. Equal similarities are rare with real vectors and common with short, near-duplicate keywords.
The comparison is a double loop over all pairs. At 150 keywords that is about twenty thousand dot products, which needs no index.
Label propagation, made deterministic
Label propagation is a simple community-detection algorithm. Every node starts with its own label. Repeatedly, each node adopts the label that most of its neighbours hold. Dense groups converge on one label.
The textbook version is random in two places: the order in which nodes are visited, and the choice when two labels tie. Both are removed here.
labels = list(range(n))
for _ in range(max_iter):
changed = False
for i in range(n):
if not adj[i]:
continue
weight_by_label: dict[int, float] = {}
for j, w in adj[i]:
weight_by_label[labels[j]] = weight_by_label.get(labels[j], 0.0) + w
# heaviest label wins, ties go to the smallest label
best_label = min(weight_by_label, key=lambda lb: (-weight_by_label[lb], lb))
if best_label != labels[i]:
labels[i] = best_label
changed = True
if not changed:
break
| Source of randomness in the usual algorithm | What this version does |
|---|---|
| Initial labels | Each node’s own index |
| Visiting order | Index order, the same every pass |
| Tie between labels | The smallest label |
| Stopping | When a full pass changes nothing, or after 40 passes |
The vote is weighted by edge weight, so a strongly similar neighbour counts for more than a marginal one. Updates are applied in place, which lets a label spread across a cluster within one pass.
Determinism continues after clustering. Clusters are numbered by total search volume, largest first, with the smallest member index as the tie-break. Members are listed by volume and then alphabetically. Two runs over the same input produce identical output down to the order of the lists.
Names and stages
Names. A small model is given each cluster’s keywords and asked for a short label, as structured output, with a 20-second limit. Only the label is used. If the call fails or times out, the cluster is labelled with its highest-volume keyword. The request waits at most 20 seconds for names, and a cluster is never shown unnamed.
Stages. Each keyword is classified into a funnel stage by a rule: lists of terms that signal a decision, then consideration, then awareness, and the keyword’s search intent as the default. A cluster takes the stage that wins a vote of its keywords weighted by volume.
Edges shown. The output keeps only edges inside a cluster. Edges between clusters are left out of the picture.
When embeddings are not available
The embedding call is best-effort. With no API key, or on any failure, it returns nothing, and the journey returns an empty graph with a field saying why. The route does not raise. The rest of the keyword explorer, which does not depend on embeddings, keeps working.
The feature itself sits behind a flag checked in the handler. With the flag off the route is still registered and answers with a clear “feature disabled” error, so the client can tell a disabled feature from a missing one.
Reuse
The two functions are small enough to reuse. A second view groups related searches into personas. It builds its graph a different way, from rank-weighted related-search links, and then calls the same label propagation, with a merge step and an embedding-based tie-break of its own.
Tests
| Test | Asserts |
|---|---|
test_cosine_knn_links_within_blobs_only | Two separated groups of vectors get no edge between them |
test_cosine_knn_tau_filters_all | A floor above every similarity yields no edges |
test_cluster_keywords_two_communities | Two communities come out as two clusters |
test_cluster_singleton_when_no_edges | A keyword with no edges is its own cluster |
test_embed_texts_without_key_degrades_to_none | No key means no vectors, not an exception |
test_build_semantic_graph_degrades_when_embeddings_none | The graph degrades to empty with a reason |
test_build_graph_llm_degrade_keeps_representative_labels | A failed naming call leaves the top-keyword labels |
test_funnel_stage_text_signals_win_over_intent | Term signals outrank the intent default |
test_build_graph_keyword_nodes_theme_colored_no_cross_edges | No edge crosses a cluster boundary in the output |
Failure modes
| What happens | What the system does |
|---|---|
| Embeddings are unavailable | An empty graph with the reason |
| The naming model fails or is slow | Top-keyword labels |
| A keyword is similar to nothing | It is a cluster of one |
| Two neighbours tie in similarity | The lower index is preferred |
| Two labels tie in a vote | The smaller label wins |
| More keywords than the cap | The highest-volume 150 are used |
Limits
- Deterministic given the vectors. The algorithm adds no randomness. If the embedding model returned different vectors for the same text, the output would change, and that is outside this code.
- Quadratic in the number of keywords. The cap of 150 is what makes the all-pairs loop acceptable.
- The thresholds are fixed. Five neighbours and a floor of 0.35 are constants, the same for every account.
- Label propagation can merge two themes joined by a bridge keyword. The floor and the neighbour limit reduce that, and they do not eliminate it.
