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

A row of five boxes: keywords, up to 150, each with search volume and intent; embed, one vector per keyword in batches; cosine kNN, the top 5 neighbours with similarity 0.35 or more; label propagation, in a fixed order with a weighted vote and ties to the smallest label; and clusters, ordered by total volume with members by volume. From embed a dashed arrow leads down to no embeddings: an empty graph with the reason, never an error. From clusters arrows lead down to names, where a small model labels them with the top keyword as fallback, and to funnel stage, a rule classifier's vote weighted by volume. A note: vectors are normalised and compared by dot product; equal similarities are ordered by index; labels start as each node's own index and are updated in a fixed order; no random seed is involved anywhere.
Figure 1. From keywords to clusters. Everything on the main row is deterministic. A model is used only to name the clusters, and a failure there falls back to the cluster's top keyword.
StageWhat happensConstant
InputRows the explorer already computed: keyword, volume, intent. Deduplicated, sorted by volume, capped150 keywords
EmbedOne vector per keyword from an embedding model, in batches512 per batch
GraphFor each keyword, its nearest neighbours by cosine similarity above a floorTop 5, similarity at least 0.35
ClusterLabel propagation over the graphAt most 40 passes
NameA small model proposes a label per cluster, with a time limit20 seconds
StageEach cluster is placed in a funnel stage by a vote of its keywordsWeighted 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 algorithmWhat this version does
Initial labelsEach node’s own index
Visiting orderIndex order, the same every pass
Tie between labelsThe smallest label
StoppingWhen 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

TestAsserts
test_cosine_knn_links_within_blobs_onlyTwo separated groups of vectors get no edge between them
test_cosine_knn_tau_filters_allA floor above every similarity yields no edges
test_cluster_keywords_two_communitiesTwo communities come out as two clusters
test_cluster_singleton_when_no_edgesA keyword with no edges is its own cluster
test_embed_texts_without_key_degrades_to_noneNo key means no vectors, not an exception
test_build_semantic_graph_degrades_when_embeddings_noneThe graph degrades to empty with a reason
test_build_graph_llm_degrade_keeps_representative_labelsA failed naming call leaves the top-keyword labels
test_funnel_stage_text_signals_win_over_intentTerm signals outrank the intent default
test_build_graph_keyword_nodes_theme_colored_no_cross_edgesNo edge crosses a cluster boundary in the output

Failure modes

What happensWhat the system does
Embeddings are unavailableAn empty graph with the reason
The naming model fails or is slowTop-keyword labels
A keyword is similar to nothingIt is a cluster of one
Two neighbours tie in similarityThe lower index is preferred
Two labels tie in a voteThe smaller label wins
More keywords than the capThe 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.