LLM Classification at Scale: Embeddings + Logistic Regression vs Prompting
Routing tickets, tagging feedback, moderating content: most AI features are classification in disguise. Here is when a prompted LLM wins, when a 20-line embedding classifier is 100x cheaper, and how to combine them.
Most "AI features" shipped in production are classification wearing a costume. Route this support ticket. Tag this piece of feedback. Is this message spam, a refund request, or a bug report? Flag this document as containing PII.
The default move is to write a prompt, call a frontier model, and parse the label. It works on day one. Then volume grows to a million items a month, latency creeps to 800 ms, the bill arrives, and someone asks why a task with eight fixed labels needs a model that can write poetry.
This post compares the two practical approaches, shows runnable code for both, and gives you a decision rule plus a hybrid that usually beats either alone.
The two approaches
Prompted LLM classification. You describe the labels in a prompt, optionally add a few examples, and ask the model to pick one (ideally with structured outputs so the label is constrained to an enum).
Embedding classifier. You embed each text once with an embedding model, then train a small classifier (logistic regression, or even k-nearest-neighbours) on labelled examples. At inference you embed the new text and run the classifier. No generation involved.
The key difference: the LLM reasons about your instructions at inference time. The embedding classifier learns your label boundaries from data at training time.
Why the embedding classifier is so cheap
An embedding call is a single forward pass with no output tokens, and embedding models are priced far below generation models. Check current prices on your provider's pricing page, but the gap is typically one to two orders of magnitude per item. Latency is also lower and far more predictable, because there is no variable-length generation.
Once you have the vectors, the classifier itself runs in microseconds on a CPU. You can also cache embeddings, so reclassifying with new labels costs nothing in API calls.
Code: an embedding classifier in about 25 lines
This uses scikit-learn and any embedding provider. The embed function is a placeholder; swap in your provider's SDK (check its docs for batching limits).
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
def embed(texts: list[str]) -> np.ndarray:
# Replace with your provider's batch embedding call.
# Must return an array of shape (len(texts), dim), L2-normalised.
raise NotImplementedError
texts, labels = load_labelled_tickets() # e.g. 2,000 hand-labelled rows
X = embed(texts)
X_train, X_test, y_train, y_test = train_test_split(
X, labels, test_size=0.2, stratify=labels, random_state=42
)
clf = LogisticRegression(max_iter=2000, class_weight="balanced")
clf.fit(X_train, y_train)
print(classification_report(y_test, clf.predict(X_test)))
def classify(text: str):
probs = clf.predict_proba(embed([text]))[0]
i = int(np.argmax(probs))
return clf.classes_[i], float(probs[i])
Two details matter. First, class_weight="balanced" stops a dominant label from swallowing rare ones. Second, predict_proba gives you a confidence score for free, which is the hook for the hybrid design below.
Code: the prompted LLM baseline
Use a constrained schema so the model cannot invent a label. Here is a TypeScript sketch using JSON schema style structured output; check your provider's docs for the exact parameter names.
const LABELS = ["billing", "bug", "feature_request", "account_access", "other"] as const;
const schema = {
type: "object",
properties: {
label: { type: "string", enum: LABELS },
reason: { type: "string" },
},
required: ["label", "reason"],
additionalProperties: false,
};
export async function classifyWithLLM(text: string) {
const system = `Classify the support ticket into exactly one label.
- billing: charges, invoices, refunds
- bug: something is broken
- feature_request: asks for new capability
- account_access: login, password, SSO
- other: anything else
If two labels fit, choose the one the customer needs resolved first.`;
// Call your provider with `system`, the ticket text, and `schema` as the
// response format. Parse and return the validated JSON.
return callModel({ system, user: text, schema });
}
Notice the tie-break rule in the prompt. Ambiguity rules are where most prompt-based classifiers quietly win or lose accuracy.
Comparison
| Dimension | Prompted LLM | Embedding + classifier |
|---|---|---|
| Labelled data needed | 0 to ~20 examples | Hundreds to thousands |
| Cost per item | Highest (input + output tokens) | Very low (input only, often cached) |
| Latency | Hundreds of ms, variable | Tens of ms, stable |
| Changing labels | Edit the prompt | Relabel and retrain |
| Handles nuanced rules ("refund only if within 30 days") | Yes | Poorly |
| Calibrated confidence | Weak (self-reported) | Good (probabilities) |
| Explainability | Free-text reason | Nearest examples, coefficients |
| Behaviour drift on model upgrade | Yes, can shift silently | None once trained |
| Best when | Cold start, rules, low volume | High volume, stable taxonomy |
The decision rule
Ask three questions in order.
- Do you have labelled data? If not, start with the LLM. It is also the fastest way to generate labels (more below).
- Is the label defined by semantics or by rules? "Is this about billing?" is semantic and embeds well. "Is this eligible for a refund under policy X?" needs reasoning, so use the LLM.
- What is your volume? Under roughly ten thousand items a month, engineering time costs more than API spend. Above a million, the gap dominates.
The hybrid that usually wins
Use the cheap classifier as a first pass and send only uncertain items to the LLM:
CONF_THRESHOLD = 0.85
def route(text: str):
label, conf = classify(text) # embedding classifier
if conf >= CONF_THRESHOLD:
return {"label": label, "source": "embed", "conf": conf}
llm = classify_with_llm(text) # expensive path
return {"label": llm["label"], "source": "llm", "conf": None}
If 80 percent of traffic clears the threshold, you pay LLM prices on only 20 percent of it. Pick the threshold from a validation set, not by feel: plot accuracy of the embedding classifier against its confidence bucket and choose the point where accuracy meets your target.
Then close the loop. Every item the LLM handles is a new labelled example (after spot-checking). Feed those back into training, and the share that needs the LLM shrinks over time.
Use the LLM to bootstrap labels
The cold-start problem for the embedding route is getting a few thousand labels. A practical workflow:
- Run the LLM on a few thousand unlabelled items.
- Hand-review a random sample of 200 to estimate its accuracy, and fix the prompt until it clears your bar.
- Train the embedding classifier on the LLM labels.
- Evaluate the classifier on a human-labelled held-out set, never on LLM labels alone, or you only measure agreement with the teacher's mistakes.
This is a lightweight form of distillation, and it works well when the label space is stable.
Evaluate properly
Accuracy alone hides problems. Track:
- Per-class precision and recall. A 95 percent overall score can hide a 40 percent recall on the rare class you care about (for example, "security incident").
- Confusion matrix. It shows which label pairs are being swapped, which usually points to a vague label definition rather than a model problem.
- Calibration. If you route on confidence, check that 0.9 confidence really means roughly 90 percent correct.
- Cost and p95 latency per item, measured end to end.
Common pitfalls
- Label leakage in the split. Near-duplicate tickets (a customer pasting the same error ten times) land in both train and test, inflating scores. Deduplicate or group-split by customer or thread.
- Trusting LLM self-reported confidence. Asking a model "how confident are you, 0 to 1?" yields poorly calibrated numbers. If you need routing by confidence, prefer classifier probabilities or log-probabilities where your provider exposes them.
- No "other" label. Without an escape hatch, every out-of-scope input is forced into a wrong bucket. Include "other" and monitor its share; a rising share signals taxonomy drift.
- Changing the embedding model silently. Vectors from different models are not comparable. Pin the model version, store it next to your classifier, and retrain on upgrade.
- Skipping the baseline. Try TF-IDF plus logistic regression first. For keyword-driven labels it is sometimes within a few points of embeddings at near-zero cost, and it tells you how hard the problem really is.
- Ignoring class imbalance. Use balanced weights or resampling and judge on per-class metrics.
- Never refreshing. Language and products change. Schedule periodic sampling of production items for human labelling and track accuracy over time.
Checklist before you ship
- Labelled, deduplicated eval set that humans reviewed
- Baseline numbers for LLM, embedding classifier, and TF-IDF
- An "other" or "abstain" path
- Confidence threshold chosen from validation data
- Embedding model version pinned and recorded
- Per-class metrics and cost per item on a dashboard
- A weekly sample of live predictions sent for human review
Next steps
Take one classification task you currently run through a prompt. Pull a thousand recent items, get a human-reviewed label set for a few hundred, and measure three systems side by side: your current prompt, an embedding classifier, and the hybrid. Compare accuracy per class, p95 latency, and cost per thousand items. The numbers will tell you where to spend model budget and where to stop.
Designing evals, picking cost-effective architectures, and shipping features like this to production is what we practise in the Joinloop AI Engineering cohort.
Want to build this yourself?
Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.