Sorting a text into several categories at once used to take masses of annotated data and a model to train. An LLM and a few examples shorten the road. They do not spare you from measuring.
By Alexis Blandin and Martin Labenne · 10 min read
In a library, a book takes up only one spot on the shelf. In the catalog, it can take up several: an essay on public debt files under politics and under economics. And some books fit none of the planned boxes.
Text data poses the same problem. A customer review, a support ticket, a news story rarely deal with a single topic. Labeling them is multi-label classification: assigning each text zero, one or several labels. The problem shows up everywhere, from social media tagging to medical diagnosis, through news article categorization and product recommendation.
We took another road than training a model: handing the sorting to a large language model. The shortcut is real. It has a price, and it moves rigor more than it removes it.
“Election debate highlights key economic policies.”
Labels are not independent. A text filed under politics is more likely to also be filed under economy than under entertainment: the presence of one label changes the probability of the others. A good model learns these links on top of each label.
These labels are written in two ways: a list per text, or one binary column per label, set to 1 when the label applies. The second form is the one measurement tools expect.
| Text | List | Pol. | Eco. | Sports | Ent. |
|---|---|---|---|---|---|
| Government passes new healthcare reform. | politics | 1 | 0 | 0 | 0 |
| Stock market hits new highs amid economic boom. | economy | 0 | 1 | 0 | 0 |
| Celebrity singer releases new music video. | entertainment | 0 | 0 | 0 | 1 |
| Local sports team wins championship game. | sports | 0 | 0 | 1 | 0 |
| Election debate highlights key economic policies. | politics economy | 1 | 1 | 0 | 0 |
| AI will take on the world. | [ ] | 0 | 0 | 0 | 0 |
The difficulty lies in the arithmetic.
Training a model then takes a large amount of annotated data. The practical question becomes: what do you do when you have neither that data nor the means to produce it?
What a hand-trained classifier costs.
The classic answer goes through a natural language processing project, NLP, in three steps.
Lowercasing, removing punctuation and digits, stemming or lemmatization.
Bag of words, n-grams.
Model choice, hyperparameter tuning, validation.
Each step takes expertise, and multi-label adds two difficulties.
Imbalance. Some labels show up everywhere, others almost never. The wider the gap, the harder training gets.
Correlation. Labels depend on one another, and the model has to learn those dependencies on top of the labels themselves.
From preprocessing to validation, the road eats time and resources before the first useful prediction.
An already trained model, an API, a few examples.
Large language models change the equation. Trained on huge volumes of text, they summarize, translate and analyze sentiment in most languages. Classifying a text is within their skills, for three reasons.
Simple. Providers expose an API you can call from any language. No machine learning expertise needed, and the text does not even need preprocessing.
Cheaper. The best language models are neural networks, which run fast on GPUs. Setting up an equipped instance, in the cloud or on premises, weighs down deployment and operations. For short texts, paying a provider for inference by the token, a fragment of a word, often comes out cheaper.
Tunable. One or two examples slipped into the instructions are enough to raise the quality of predictions.
That leaves the usual objection: an LLM would never answer the same thing twice. True in general, and rare on a simple classification task. The OpenAI API also lets you pin down the randomness.
# pin down randomness as far as the API allows temperature=0, seed=424242,
The result becomes almost deterministic. For classification, almost is enough.
No training set.A test set, always.
The LLM spares you from training a model. It does not spare you from checking that it classifies your own texts well. For multi-label, a good test set:
Refreshing it with fresh data lets you track quality under real conditions, on texts the prompt has never seen.
Every word the model writes is paid for, in money and in time.
Since LLMs arrived, prompting techniques keep multiplying: few-shot, chain of thought, tree of thoughts, and a new one every month. They do not use the same number of tokens, and that number decides cost and latency.
A few dozen lines of Python.
The classifier relies on the OpenAI API. It picks between zero and four labels: sports, politics, economy and entertainment. It all comes down to the message stack sent to the model.
messages = [ {"role": "system", "content": "You are a multi-label classifier. Return the tags as a " "list separated by commas. If no tags apply, return nothing. " "Available tags: sports, politics, economy, entertainment."}, # example 1: two labels {"role": "user", "content": "Text: 'Election debate highlights key economic policies.'"}, {"role": "assistant", "content": "Tags:politics,economy"}, # example 2: no label {"role": "user", "content": "Text: 'AI will take on the world.'"}, {"role": "assistant", "content": "Tags:"}, # the text to classify {"role": "user", "content": f"Text: '{content_txt}'"},]
The model's answer is still free text. It has to be cleaned: strip the prefix, split, trim the spaces. Then filtered, because the model can invent a label. Intersecting with the allowed list erases it.
ALLOWED = ["sports", "politics", "economy", "entertainment"] def parse_labels(completion) -> list[str]: text = completion.choices[0].message.content text = text.replace("Tags:", "").strip() if not text: return [] labels = [label.strip() for label in text.split(",")] return sorted(set(labels) & set(ALLOWED)) # the guardrail
Few-shot has a limit: the more labels, the more the model hesitates, and precision drops. When labels form a hierarchy, a cascade gets around the problem. A first call picks the floor, a second, specialized one, picks the shelf.
first call, generalist
fine-grained labels
fine-grained labels
Otherwise, you have to test costlier techniques that are less sensitive to the number of labels.
One last plumbing detail. Classifying a backlog of thousands of texts quickly hits the provider's rate limit. The ratelimit package settles it with two decorators: beyond 50 calls a minute, extra calls wait for the next window instead of failing.
from ratelimit import limits, sleep_and_retry @sleep_and_retry # beyond that: wait, then retry@limits(calls=50, period=60) # 50 calls per minutedef get_chat_completion(messages): return client.chat.completions.create( model=MODEL_NAME, messages=messages, temperature=0, seed=424242, )
Trace, measure, compare.
In production, every call must leave a trace: the input, the output, the number of tokens and the duration. These traces show good and bad predictions, the real cost and the latency. A longer sequence takes longer to generate. Tools like LangSmith or Phoenix make these traces readable.
Quality is measured continuously, on fresh data, through human review or through a second LLM tasked with judging the first: LLM as a judge. Each prompt version is kept with its classification report, to compare versions on the same metrics.
That leaves choosing those metrics. In multi-label, the same prediction gets very different scores depending on the rule applied.
All or nothing.
1 wrong label out of 4.
1 in common out of 2 in total.
Nothing wrong, one miss.
The choice depends on the error you fear. Precision avoids false positives, recall avoids misses, F1 balances the two. To aggregate over several labels, scikit-learn offers four averages.
A single call to classification_report gives precision, recall, F1 and support, per label and for each average.
mlb = MultiLabelBinarizer().fit([ALLOWED])y_true = mlb.transform(labels_true)y_pred = mlb.transform(labels_pred) accuracy_score(y_true, y_pred) # exact matchhamming_loss(y_true, y_pred)jaccard_score(y_true, y_pred, average="samples")classification_report(y_true, y_pred, target_names=mlb.classes_)
An LLM does not get rid of the dataset.It moves it from training to testing.
The shortcut is real: an API, a few examples, no preprocessing pipeline and no model to train. But rigor moves elsewhere. It settles in the test set, in the traces, in the metrics and in the prompt history. That is where you find out whether the book is on the right shelf.