liveBook · Manning

K-nearest neighbors

As explained in Building LLM Applications with DSPy

The k examples most similar to a query according to a measure of similarity.

For a flight-query intent classifier, examples similar to the current utterance may be more useful than a fixed set of demonstrations. K-nearest neighbors selects the k most similar training utterances for each language-model call, so the prompt can change with the input. section 5.5

A DSPy KNN optimizer stores and encodes the training set during compilation without calling the language model. It chooses demonstrations when an input arrives. Because each set only needs to suit that input, fewer examples may be enough. section 5.5

Listing 5.12 KNNFewShot optimizer
import dspy
from dspy import KNNFewShot
from sentence_transformers import SentenceTransformer

encoder_func = SentenceTransformer(
"sentence-transformers/all-MiniLM-L12-v2", 
token=False).encode

knn_optimizer = KNNFewShot(
    k=3,
    trainset=train_set,
    vectorizer=dspy.Embedder(encoder_func)
)

optimized_module = knn_optimizer.compile(dspy.Predict(ClosedIntentSignature))
prediction = optimized_module(**dev_set[0].with_inputs())
print(lm.inspect_history(n=1))

The Python listing configures a sentence-transformer encoder, sets k to three, and compiles a DSPy predictor with KNNFewShot. section 5.5

How Building LLM Applications with DSPy covers it

How deep it goes
Explains when examples are encoded and selected, then shows optimizer configuration; does not specify a similarity metric.
Examples
Illustrates flight-query intent classification and a Python configuration that retrieves three demonstrations.
What you can do after
Apply it via DSPy KNNFewShot to compile a predictor with dynamically selected demonstrations.
How it connects
Connects nearest-neighbor retrieval to text encoding, few-shot prompting, and intent classification.

Also explained in

Compare how 3 books explain k-nearest neighbors →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building LLM Applications with DSPy. The section links point to the parts of the book it draws on.